Built-in pointer variable definition

This is a question about built-in variables and their uniqueness in several translation units. Consider the following code that separates a string literal in two translation units:

Hdr.h file:

inline const char* const str = "hello world"; 

File tu0.cpp:

 #include <cstdio> #include "hdr.h" void foo() { printf("tu0: &str=%p, str=%p\n", &str, str); } 

File tu1.cpp:

 #include <cstdio> #include "hdr.h" extern void foo(); int main() { foo(); printf("tu1: &str=%p str=%p\n", &str, str); } 

For completeness, here is how I compile them (on linux, 64-bit, binutils 2.28):

 $ CXX -c -std=c++1z tu0.cpp -o tu0.o $ CXX -c -std=c++1z tu1.cpp -o tu1.o $ CXX -std=c++1z tu*.o -o a.out 

With CXX = clang-4.0, both str and & str are identical:

 tu0: &str=0x400608 str=0x4005f9 tu1: &str=0x400608 str=0x4005f9 

But with g ++ versions 7.1 and 7.2, I get an unexpected result:

 tu0: &str=0x4005d8 str=0x4005b4 tu1: &str=0x4005d8 str=0x4005e0 

Ok, I really have a few questions (but they are all related):

  • Should str and & str have the same value in all translation units?

  • N4687 [dcl.inline] / 6 says that the built-in variable must have the same definition in each translation unit. Does "definition" refer to the source hello world token or to the value of the string literal pointer "hello world"?

  • How does GCC manage to get the same address for str, but different values โ€‹โ€‹depending on where this variable is accessed? And this leads to the last question:

  • Does the built-in variables take longer to execute (on every access) than the usual extern declarations approach with manual definition in one translation unit?

+5
source share

Source: https://habr.com/ru/post/1271250/


All Articles