reference with constexpr causes multiple definition error

不打扰是莪最后的温柔 提交于 2019-12-11 10:22:53

问题


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?

来源:https://stackoverflow.com/questions/15291867/reference-with-constexpr-causes-multiple-definition-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!