尝试使用命名空间中的变量时,我得到一个未定义的引用。我创建了一个头文件和一个包含命名空间的实现文件,并试图在另一个文件中使用命名空间......
编辑:
//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'
编辑实际代码
//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);