C ++ 17 inline변수
이 멋진 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://en.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에서 테스트되었습니다.