C ++ 17inline变量
这个很棒的C ++ 17功能使我们能够:
main.cpp
#include <cassert>
#include "notmain.hpp"
int main() {
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();
#endif
notmain.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
./main
GitHub上游。
另请参阅:内联变量如何工作?
内联变量的C ++标准
C ++标准保证地址相同。C ++ 17 N4659标准草案
10.1.6“内联说明符”:
6具有外部链接的内联函数或变量在所有翻译单元中应具有相同的地址。
cppreference https://zh.cppreference.com/w/cpp/language/inline解释说,如果static未给出,则它具有外部链接。
内联变量实现
我们可以观察到它是如何实现的:
nm main.o notmain.o
其中包含:
main.o:
U _GLOBAL_OFFSET_TABLE_
U _Z12notmain_funcv
0000000000000028 r _ZZ4mainE19__PRETTY_FUNCTION__
U __assert_fail
0000000000000000 T main
0000000000000000 u notmain_i
notmain.o:
0000000000000000 T _Z12notmain_funcv
0000000000000000 u notmain_i
并man nm说u:
“ u”符号是唯一的全局符号。这是对ELF符号绑定的标准集合的GNU扩展。对于这样的符号,动态链接程序将确保在整个过程中只有一个使用此名称和类型的符号。
因此我们看到有专门的ELF扩展程序。
已在GCC 7.4.0,Ubuntu 18.04上测试。