This is relevant: https://stackoverflow.com/questions/45987571/difference-between-constexpr-and-static-constexpr-global-variable
I made the following experiment:
s.h
:
0constexpr const char* s{"aabbcc"};
a.cc
:
0#include "s.h"
1#include <stdio.h>
2void a()
3{
4 printf("a(): %p, %s\n", &s, s);
5}
b.cc
:
0#include "s.h"
1#include <stdio.h>
2void b()
3{
4 printf("b(): %p, %s\n", &s, s);
5}
main.cc
:
0void a();
1void b();
2int main(int, char**)
3{
4 a();
5 b();
6 return 0;
7}
0$ clang++-devel -c a.cc -o a.o
1$ clang++-devel -c b.cc -o b.o
2$ clang++-devel -c main.cc -o main.o
3$ clang++-devel a.o b.o main.o -o main
4$ ./main
5a(): 0x200578, aabbcc
6b(): 0x200580, aabbcc
Also checked that the main
executable contains the string aabbcc
just once, so it is not duplicated. But there are two different pointers pointing to it.
Then I changed the header s.h
to:
0inline constexpr const char* s{"aabbcc"};
And re-ran:
0$ ./main
1a(): 0x200578, aabbcc
2b(): 0x200578, aabbcc
now it is the same pointer.
So, I added inline
to the variables involved.