是否可以声明一个变量extern constexpr并在另一个文件中定义它?
我试过了,但是编译器给出了错误:
constexpr变量'i‘的声明不是定义
在.h中:
extern constexpr int i;在.cpp中:
constexpr int i = 10; 发布于 2015-05-13 07:56:17
不,你不能这样做,这是标准规定(第7.1.5节):
1该指定符仅适用于变量或变量模板的定义、函数或函数模板的声明或文字类型的静态数据成员的声明(3.9)。如果函数、函数模板或变量模板的任何声明都有一个constexpr说明符,那么它的所有声明都应该包含constexpr说明符。注意:一个显式的专门化可以与相对于constexpr说明符的模板声明不同。不能声明函数参数。-尾注
标准列举的一些例子如下:
constexpr void square(int &x); // OK: declaration
constexpr int bufsz = 1024; // OK: definition
constexpr struct pixel { // error: pixel is a type
int x;
int y;
constexpr pixel(int); // OK: declaration
};
extern constexpr int memsz; // error: not a definition发布于 2018-12-22 15:08:11
inline变量C++17
这个令人敬畏的C++17特性允许我们:
constexprmain.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
// Both files see the same memory address.
assert(¬main_i == notmain_func());
assert(notmain_i == 42);
}notmain.hpp
#ifndef NOTMAIN_HPP
#define NOTMAIN_HPP
inline constexpr int notmain_i = 42;
const int* notmain_func();
#endifnotmain.cpp
#include "notmain.hpp"
const int* notmain_func() {
return ¬main_i;
}编译和运行:
g++ -c -o notmain.o -std=c++17 -Wall -Wextra -pedantic notmain.cpp
g++ -c -o main.o -std=c++17 -Wall -Wextra -pedantic main.cpp
g++ -o main -std=c++17 -Wall -Wextra -pedantic main.o notmain.o
./mainC++标准保证地址是相同的。C++17 N4659标准草案 10.1.6“内联说明符”:
6具有外部链接的内联函数或变量在所有翻译单元中应具有相同的地址。
https://en.cppreference.com/w/cpp/language/inline解释说,如果没有给出static,那么它就有外部链接。
另见:内联变量是如何工作的?
GCC测试7.4.0,Ubuntu 18.04。
发布于 2015-05-13 07:48:11
不是的。外执法官没有任何意义。请阅读http://en.cppreference.com/w/cpp/language/constexpr
即位
必须立即构造或分配一个值。
https://stackoverflow.com/questions/30208685
复制相似问题