我有以下5個文件:global_vars.h,global_vars.cpp content.h content.cpp main.cpp。如何使用C++ extern常量變量作爲不同文件中的模板參數
global_vars.h
#ifndef global_vars_h
#define global_vars_h
namespace Constants{
extern const unsigned int b;
}
#endif
global_vars.cpp
#include "global_vars.h"
namespace Constants{
extern const unsigned int b(5);
}
content.h
#ifndef CONTENT_H_
#define CONTENT_H_
#include "global_vars.h"
#include <bitset>
struct a{
std::bitset<Constants::b> s;
int a=10;
};
#endif
content.cpp
#include "content.h"
a xVar;
的main.cpp
#include "content.h"
int main(){
return 0;
}
我收到以下錯誤:
In file included from content.cpp:1:0:
content.h:11:31: error: the value of ‘Constants::b’ is not usable in a constant expression
In file included from content.h:4:0,
from content.cpp:1:
global_vars.h:6:28: note: ‘Constants::b’ was not initialized with a constant expression
extern const unsigned int b;
我必須使用常量:: B比content.cpp其他文件/ .H(其它位集),以及使我怎麼能這樣做呢?感謝幫助。
謝謝
global_vars.cpp中不應該有關鍵字「extern」。它阻止編譯器在二進制global_vars.o中創建變量。你會得到一個鏈接錯誤,說這個變量是未定義的。 – iksess