const 修饰的对象具有局部属性,一般将其定义在.c文件中,其他文件想访问的话就在.c对应的.h中extern一下。
那么:
application.c 如下:
#include <iostream>
#include "application.h"
constexpr int N_TEST = 10;
int
func()
{
int arra[N_TEST];
std::cout << &N_TEST << std::endl;
return 0;
}
application.h定义如下:
extern constexpr int N_TEST;
struct test_2{
int arr[N_TEST];
};
编译报错:
test g++ ./test.cc ./application.cc -std=c++11
./test.cc:8:14: error: use of undeclared identifier 'N_TEST'
int arrt[N_TEST];
^
1 error generated.
➜ test
显示N_TEST未定义 将constexpr改为const也是报错。
问题:
1. 为什么会找不到定义
2. 此种情形N_TEST该怎么设计更合理,.h文件会使用其他.c中的const常量。
constexpr 不能支持extern
int N_TEST = 10;
extern int N_TEST;
1 The constexpr specifier shall be applied only to the definition of a variable or variable template, the declaration of a function or function template, or the declaration of a static data member of a literal type (3.9). If any declaration of a function, function template, or variable template has a constexpr specifier, then all its declarations shall contain the constexpr specifier. [Note: An explicit specialization can differ from the template declaration with respect to the constexpr specifier. Function parameters cannot be declared constexpr. — end note ]
把库文件里extern constexpr int N_TEST 改成 extern N_TEST 试试