qfmeal 发表于 2016-06-21 10:19

extern const int 与const int有什么区别

代码如下:
a.h
extern const int m;
...

a.cpp
const int m=100;


main.cpp

#include "a.h"
int main(int argc,char **argv)
{
   ...
    switch( value )
    {
    case m:
      printf("m=%d\n",m);
      break;
    ...
    }
    ...
}

如上代码,a.cpp中定义了const int m;然后在a.h中extern做了声明。在main.cpp中调用了m。
这时候编译报错:
error: 'm' cannot appear in a constant-expression

请问这是为什么?应该如何修改?
编译器是:arm-unknown-nto-qnx6.6.0eabi-g++-4.7.3.exe

windoze 发表于 2016-06-21 10:51

extern const int不能拿来当constant expression用。
这不很显然么,编译器编译到那个case的时候连m到底是多少都不知道,怎么生成代码?

qfmeal 发表于 2016-06-21 11:05

谢谢   windoze

a742794196 发表于 2016-07-21 09:40

你在a.cpp中定义 const int m = 100;然后在文件的开头加上#include "a.h"   在a.h中做 extern const int m;声明,然后在 test.cpp中开头加上#include "a.h"不就可以了吗????
页: [1]
查看完整版本: extern const int 与const int有什么区别