gcc __attribute__((selectany)) alternative for linux?

拈花ヽ惹草 提交于 2021-01-27 13:23:42

问题


i would like to know if there is an alternative for __attribute__((selectany)) in linux ?

i would like to define something like that:

char * a[] = { "qwe", "zxc" };

in a header file and include it in many .c files which would be linked together. so the linker will see more than one definition of "a" and therefor will not link. i've read of this attribute (selectany), which will use only the first seen definition of "a", unfortunately it is only for ms windows. so the question is: is there an alternative method in linux ?

edit: the actual question is: is there a way to instruct the linker to use only the first seen definition and ignore any other perhaps even if they are different ? i know there are many ways to define my data, i'm not searching for solution of how to define my data, instead i would like to know if there is a way to have multiple definitions and make the linker work with the first seen...


回答1:


I think you are looking for the 'weak' gcc attribute.




回答2:


First, you should definitively give it a const attribute:

char const * a[] = { "qwe", "zxc" };

modifying string literals would lead to undefined behavior. Then to answer your question, at least partially.

Besides the approach of declaring it extern as in previous answers, the first, not recommended, way to proceed would be to declare your array static. You'd then have a copy of the array in each compilation unit that uses the array. As long as you don't want to modify the contents of the arrays (have the pointers point to different strings) this is fine, but blows up your code a bit.

If you'd just need to reference the strings in function scope and you have a C99 complying compiler you could look into using compound literals:

#define MYARRAY ((char const*const[]){ "qwe", "zxc" })

This you could then use readonly as you would expect, something like MYARRAY[1] and any decent compiler should be able to optimize such an access.




回答3:


Why not simply declare it in the header, and provide a single definition in one translation unit?




回答4:


What about declaring in the header as:

extern char * a[] = { ... }

And then define the actual a[] in only one c file:

char * a[] = { ... }


来源:https://stackoverflow.com/questions/4826612/gcc-attribute-selectany-alternative-for-linux

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