对`(匿名命名空间)::的未定义引用

Undefined reference to `(anonymous namespace)::

本文关键字:未定义 引用 命名空间      更新时间:2023-10-16

我有一个命名空间,目前正在两个类中使用。当我试图编译我的项目时,我会收到错误,但我的命名空间不是匿名的!

我的一个课程是这样的:

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

我的命名空间如下:

//specificMath.nsp.h
#ifndef specificMath
#define specificMath
namespace specificMath {
     double math_function1(double, double, double);
     double math_function1(double);
     //more functions
}

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

当我尝试编译时,它似乎编译得很好,但当链接时(我一直在做"清理"以确保它使用新文件),我会收到一个错误,说:

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

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

我这样编译:

g++ -I. -c -w *.h *.cpp

然后。。。

g++ -o myProgram *.o 

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

#ifndef specificMath
#define specificMath
namespace specificMath {

预处理器运行后

namespace {

宏总是使用所有大写字母,并且永远不要在它们前面加下划线。

#ifndef SPECIFIC_MATH_FUNCTIONS

例如。

它认为它是一个匿名命名空间,因为您使用使其匿名

#define specificMath

所以"specificMath"将扩展为零。

你可以给定义一个标识符,例如

#define specificMath specificMath

或者只是不为include保护和命名空间使用相同的标识符。

#ifndef SPECIFIC_MATH_H
#define SPECIFIC_MATH_H
namespace specificMath { ... }
#endif

您的ifdef宏正在干扰您的mamespace名称。