[英]Undefined reference to `(anonymous namespace)::
我有一個當前在兩個類中使用的名稱空間。 當我嘗試編譯項目時,出現該錯誤,但我的名稱空間不是匿名的!
我的一個班級看起來像這樣:
//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
}
當我嘗試編譯時,它似乎可以正常編譯,但是在鏈接時(並且我一直在做“ make clean”以確保它正在使用新文件),我收到一條錯誤消息:
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
或只是對於包含保護和名稱空間不要使用相同的標識符。
#ifndef SPECIFIC_MATH_H
#define SPECIFIC_MATH_H
namespace specificMath { ... }
#endif
您的ifdef宏正在干擾您的mamespace名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.