Undefined Reference to namespaces in C++

≡放荡痞女 提交于 2020-01-07 05:38:08

问题


I am getting an undefined reference when trying to use variables from my namespace. I created a header file and an implementation file with the namespace in it and am trying to use the namespace in another file...

EDITED:

//first.h
namespace first
{
  extern int var;
  extern int multiplyVar(int);
}

//first.cpp
namespace first
{
  int var = 5;
  int multiplyVar(int mult)
  {
    return mult * var;
  }
}

//someOtherFile.h
#include "first.h"

//someOtherFile.cpp
first::var = 3;
int newVar = first::multiplyVar(3);

//error
undefined reference to  'first::multiplyVar(...)'
undefined reference to 'first::var'

EDIT Actual Code

//jFork.h
#ifndef JFORK_H
#define JFORK_H

#include <iostream>
#include <string>

using namespace std;

namespace jFork
{
  extern int sockfd, newsockfd;
  int j_fork(string);
}

#endif //JWDSFORK_H

//jFork.cpp
namespace jFork
{
  int sockfd = 0, newsockfd = 0;

  int j_fork(string name)
  {
    cout<<"Preparing to fork: "<<name<<endl;

    int rv = fork();

    cout<<"Called fork(): "<<name<<endl;

    switch(rv)
    {
    case -1:
        cout<<"Exiting..."<<endl;
        exit(EXIT_FAILURE);
        break;
    case 0:
        if(sockfd)
        {
            cout<<"Closing sockfd: "<<name<<endl;
            close(sockfd);
            sockfd = 0;
        }

        if(newsockfd)
        {
            cout<<"Closing newsockfd: "<<name<<endl;
            close(newsockfd);
            newsockfd = 0;
        }

        break;
    default:
        cout<<"Preparing to sleep: "<<name<<endl;
        sleep(1);
        cout<<"Woke up from sleep"<<name<<endl;
        break;
    }

    return rv;
  }
}

//server.cpp
int pid = jFork::j_fork(name);

回答1:


Note no extern for function declrations and defining the symbols in the namespace in the implementation file.

//first.h
namespace first
{
  extern int var;
  extern int multiplyVar(int);
}

//first.cpp
var = 5;
extern int multiplyVar(int mult)
{
  return mult * var;
}

Should be

//first.h
namespace first
{
  extern int var;
  int multiplyVar(int);
}

//first.cpp
namespace first
{
   int var = 5;
   int multiplyVar(int mult)
   {
     return mult * var;
   }
}



回答2:


Try:

extern int first::multiplyVar(int mult)

Your definition is in the global namespace.

You could also wrap all the definitions in the CPP file in a namespace block, but my preference is to not do it this way.



来源:https://stackoverflow.com/questions/10535221/undefined-reference-to-namespaces-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!