"multiple definition of" 错误

来源:互联网 发布:厦门大学软件学院分数 编辑:程序博客网 时间:2024/04/29 05:47
"multiple definition of" 错误

在global.h定义了一个常量字符串,在多个cpp中包含该global.h.

// file: global.h
#ifndef GLOBAL_H
#define GLOBAL_H
const char * STR_TEST = "Hello world!";
#endif


结果链接时出现错误:
multiple definition of ‘STR_TEST’
虽然改为#define肯定行,但是尽量应该用const量取代宏定义。

这里有个概念性错误。
const 变量默认是 static 的,
但带有 const 的不一定是 const 变量.
此处 STR_TEST 并不是常量,而是指向常量字符串的变量。

改为
const char * const STR_TEST = "Hello world!";
就可以了。

不过我又觉得改为
const char STR_TEST[] = "Hello world!";
更好。