在C ++中对命名空间的未定义引用 [英] Undefined Reference to namespaces in C++

查看:776
本文介绍了在C ++中对命名空间的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试使用我的命名空间中的变量时,我得到一个未定义的引用.我创建了一个头文件和一个带有名称空间的实现文件,并试图在另一个文件中使用名称空间...

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...

已编辑

//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);

推荐答案

对于函数定义和在实现文件中的命名空间中定义符号,请注意没有extern.

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;
}

应该是

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

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

这篇关于在C ++中对命名空间的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆