c++多定义链接错误与.h中声明的const

C++ multiple definition linking error with const declared in .h

本文关键字:声明 const 定义 链接 错误 c++      更新时间:2023-10-16

我使用了一些在

中定义的常量

Constanst.h

#ifndef __CONSTANTS_H__
#define __CONSTANTS_H__ 
namespace A{
    namespace B{
    const int FIRST = 1;
    const int SECOND = 2;
    }
}
#endif

我包括这个文件从2个不同的。cpp (a.p和b.p)

gcc版本3.2.3给了我"多重定义"链接错误

我解决这个问题的方法是添加另一个"File.h",其中包含" constants .h",并将相同的常量声明为"extern"

有人能解释一下吗?我以为这是C的问题,而不是c++

使用g++版本4.3.4:

constants.h:5: error: ISO C++ forbids declaration of `FIRST' with no type

添加类型int后,正常运行。

所以也许你应该使用一个新的编译器?使用g++代替gcc?