读书人

~头文件定义常量的有关问题~

发布时间: 2012-03-13 11:21:12 作者: rapoo

~~头文件定义常量的问题~~
大家好,编程中我需要用到两个 "全局常量 ",
const int MAX_LEN = 1024;
const char * DEFAULT_NAME = ".default ";
考虑把他们放哪时遇到了问题:
现有3个文件, a.cpp, b.cpp
1.h:

struct struct_t //全局结构体
{
char path[MAX_LEN];
char path[MAX_LEN];
};

a.cpp:
#inlcude "1.h "

b.cpp:
#inlcude "1.h "

由于多个文件会使用这两个常量我需要在头文件中定义:
1.h:
const int MAX_LEN = 1024;
const char * DEFAULT_NAME = ".default ";
struct struct_t //全局结构体
{
char path[MAX_LEN];
char name[MAX_LEN];
};
结果是连接时产生multiply defined 的错误。
听说c++会自动将头文件中的常量标以static,但还是错,于是就手动加上:
1.h:
static const int MAX_LEN = 1024;
static const char * DEFAULT_NAME = ".default ";
错误变成“warning: `const char *DEFAULT_CONF_NAME ' defined
but not used”(warning我当作错误处理),错误原因请指教:)

第三个方法,我把这两个常量定义放到a.cpp中,头文件用extern,又出现如下的错误:“ size of member `path ' is not constant”,原来是struct_t需要用到先确定值的MAX_LEN。
问题来了,我不能移动struct_t,其它文件需要它,而且这样的结构体有很多,但把把这两个常量的定义放在头文件中又出错。

请问高手,如何解决这个问题????

ps:当然,在头文件中用#define 代替常量定义就可以解决,但我想要个常量的解决方案,谢谢:)




[解决办法]
static const char * DEFAULT_NAME = ".default ";
enum{MAX_LEN = 1024};
struct struct_t //全局结构体
{
char path[MAX_LEN];
char name[MAX_LEN];
};

这样改可以。
[解决办法]
错误变成“warning: `const char *DEFAULT_CONF_NAME ' defined
but not used”(warning我当作错误处理),错误原因请指教:)
=================
定义了DEFAULT_CONF_NAME, 却没有使用它.
你就用下, 这个警告就没有了!
如果你不打算使用它, 那定义这个常量纯属多余:)
[解决办法]
1) 听说c++会自动将头文件中的常量标以static,但还是错,于是就手动加上:

-----------------------

各种编译器不一定一样,所以不要写这种代码


2)

static const int MAX_LEN = 1024;
static const char * DEFAULT_NAME = ".default ";
错误变成“warning: `const char *DEFAULT_CONF_NAME ' defined
but not used”(warning我当作错误处理),错误原因请指教:)


-----------------------

这个是说你定义了 DEFAULT_CONF_NAME 但没有使用,

把warnning等级调低就没有了


3)

extern 是在连接的是时候才检查,但

你的struct_t需要用到MAX_LEN是在编译时检查

所以包错,说 MAX_LEN 不是常量


解决办法就是

static const int MAX_LEN = 1024;
static const char * DEFAULT_NAME = ".default "; // 这个要你就用一下,要就注掉

读书人网 >C++

热点推荐