在C++中是合法的將一個常量放在頭文件中,通常C方法是將extern聲明放在頭文件中,而定義只在一個編譯單元中,但在C++中,以前的技術會導致二進制文件增加,因爲鏈接時不會刪除符號(使用gnu ld和visual studio進行測試)。有沒有很好的方法來做這些事情?我只能想到的定義或C-方式,但以後可能會少給優化房間...C++常量符號膨脹鏈接文件
[email protected]:0:/tmp$ g++ -c b.cc
[email protected]:0:/tmp$ g++ -c a.cc
[email protected]:0:/tmp$ nm a.o | c++filt | grep COOK
0000000000000000 r AI_LIKE_COOKIES
[email protected]:0:/tmp$ nm b.o | c++filt | grep COOK
0000000000000000 r AI_LIKE_COOKIES
[email protected]:0:/tmp$ g++ -o a a.o b.o
[email protected]:0:/tmp$ nm a | c++filt | grep COOK
0000000000400610 r AI_LIKE_COOKIES
0000000000400618 r AI_LIKE_COOKIES
[email protected]:0:/tmp$ cat a.h
#ifndef a_h
#define a_h
//const double A = 2.0;
//extern const double AI_LIKE_COOKIES;
const double AI_LIKE_COOKIES = 5.0;
#endif
[email protected]:0:/tmp$ cat a.cc
#include "a.h"
using namespace std;
extern void f();
//const double AI_LIKE_COOKIES = 2.0;
int main(int argc, char *argv[])
{
f();
}
[email protected]:0:/tmp$ cat b.cc
#include "a.h"
void f()
{
}
[email protected]:0:/tmp$
如果使用最小優化('-O1'),const對象將在編譯階段消失。由於它們具有內部鏈接,編譯器可以選擇將它們丟棄,因爲它們不是必需的。 –