未明确引用`(匿名命名空间)::

coc*_*nut 0 c++ namespaces compilation

我有一个名称空间,我目前在两个类中使用.当我尝试编译我的项目时,我得到了该错误,但我的命名空间不是匿名的!

我的一个类看起来像这样:

//margin.cpp
#include <math.h>
#include "margin.h"
#include "anotherClass.h"
#include "specificMath.nsp.h" //My namespace

double margin::doSomeMath(double a, double b){
    return specificMath::math_function1(0, 1, 0);
    // Just a simpler, random example
} 
Run Code Online (Sandbox Code Playgroud)

我的命名空间如下所示:

//specificMath.nsp.h
#ifndef specificMath
#define specificMath
namespace specificMath {
     double math_function1(double, double, double);
     double math_function1(double);
     //more functions
}
Run Code Online (Sandbox Code Playgroud)
 //specificMath.nsp.cpp
 #include <stdlib.h>
 #include "constants.h"
 #include "specificMath.nsp.h"

 namespace specificMath{
     double math_function1(double a, double b, double c){
          //some code
     }
     ... more functions
 }
Run Code Online (Sandbox Code Playgroud)

当我尝试编译时,似乎编译正常,但在链接时(我一直在做"make clean"以确保它使用新文件)我得到一个错误说:

margin.o: In function `margin::doSomeMath(double, double)':
margin.cpp:(.text+0x3d): undefined reference to `(anonymous namespace)::math_function1(double, double, double)'
Run Code Online (Sandbox Code Playgroud)

为什么它认为它是一个匿名命名空间?我怎样才能解决这个问题?

我编译这样做:

g++ -I. -c -w *.h *.cpp
Run Code Online (Sandbox Code Playgroud)

然后...

g++ -o myProgram *.o 
Run Code Online (Sandbox Code Playgroud)

Pup*_*ppy 6

#define的命名空间名称.在预处理器看到#define specificMath之后,它会找到之后的所有实例specificMath,并将它们替换为您所使用的内容#define,在这种情况下,它不是什么.所以它简单地消除了它.

#ifndef specificMath
#define specificMath
namespace specificMath {
Run Code Online (Sandbox Code Playgroud)

预处理器运行后

namespace {
Run Code Online (Sandbox Code Playgroud)

始终将所有大写都用于宏,并且永远不要在它们前面添加下划线.

#ifndef SPECIFIC_MATH_FUNCTIONS
Run Code Online (Sandbox Code Playgroud)

例如.