reference with constexpr causes multiple definitio

2019-08-02 09:26发布

问题:

I program for MCUs with CodeSourcery g++ lite which is based on gcc 4.7.2
I want to define peripheral objects which is located at certain address. So I try to use reference with the constexpr specifier.

for example:

typedef int& int_ref;
constexpr int_ref i = *(int*)0;

If I put that code into a header, and compile my program, I will get diagnosis like:

xx1.o:(.rodata.i+0x0): multiple definition of `i'
...
xxx.o:(.rodata.i+0x0): first defined here
collect2.exe: error: ld returned 1 exit status

It confuses me bacause the constexpr int i = 5 goes so happily with the compiler.

Of course there are alternative solutions:
1. Macros, #define i *(int*)0, which pollutes every .c/.cpp file including the header. Currently, I'm using macros.
2. static object, static constexpr int_ref i = *(int*)0;. Without some compiler-option (-fdata-sections), the compiler can't eliminate unused objects and then there would be lots of space wasted.

Is there any better way to do this?