天天看點

Cpp Primer雜記–extern const的聲明注意

Cpp Primer雜記–extern const的聲明注意

結論:在用extern const 時,在.h檔案中對const 的 object 進行的一些非聲明操作在連結時會認為是定義而可編譯而無法連結(重定義).

解釋:

錯誤代碼:

這裡多出file_2.h 嵌套在file_1.h中再include到main裡,那麼如果在file_2.h對bufSize進行了一些非聲明操作會導緻其的重定義.vs2015_Pro 出現:fatal error LNK1169.

//file_1.h
 #include "file_2.h"
 extern const int bufSize;
 //file_2.h
 extern const int bufSize = ;
 //main.c
 #include "file_1.h"
 int main()
 {
 }
           

或者file_2.h改為

//file_2.h
int get_bufSize(void)
{
    return bufSize;
}
           

正确代碼:

将定義一定寫到.cpp中

#include "file_2.h"
 extern const int bufSize;
 //file_2.h
 extern const int bufSize;
 //file_2.cpp
 extern const int bufSize = ;
 //main.c
 #include "file_1.h"
 int main()
 {
 }
           

繼續閱讀