"multiple definition of" 錯誤
在global.h定義了一個常量字符串,在多個cpp中包含該global.h.
// file: global.h
#ifndef GLOBAL_H
#define GLOBAL_H
const char * STR_TEST = "Hello world!";
#endif
結(jié)果鏈接時出現(xiàn)錯誤:
multiple definition of ‘STR_TEST’
雖然改為#define肯定行,但是盡量應(yīng)該用const量取代宏定義。
這里有個概念性錯誤。
const 變量默認(rèn)是 static 的,
但帶有 const 的不一定是 const 變量.
此處 STR_TEST 并不是常量,而是指向常量字符串的變量。
改為
const char * const STR_TEST = "Hello world!";
就可以了。
不過我又覺得改為
const char STR_TEST[] = "Hello world!"
更好。
在global.h定義了一個常量字符串,在多個cpp中包含該global.h.
// file: global.h
#ifndef GLOBAL_H
#define GLOBAL_H
const char * STR_TEST = "Hello world!";
#endif
結(jié)果鏈接時出現(xiàn)錯誤:
multiple definition of ‘STR_TEST’
雖然改為#define肯定行,但是盡量應(yīng)該用const量取代宏定義。
這里有個概念性錯誤。
const 變量默認(rèn)是 static 的,
但帶有 const 的不一定是 const 變量.
此處 STR_TEST 并不是常量,而是指向常量字符串的變量。
改為
const char * const STR_TEST = "Hello world!";
就可以了。
不過我又覺得改為
const char STR_TEST[] = "Hello world!"
更好。