Linux 的 gcc __attribute__((selectany)) 替代品?
我想知道 linux 中是否有 __attribute__((selectany)) 的替代方案?
我想定义类似的东西:
char * a[] = { "qwe", "zxc" };
在头文件中并将其包含在许多链接在一起的 .c 文件中。 因此链接器将看到“a”的多个定义,因此不会链接。我读过这个属性(selectany),它将仅使用第一个看到的“a”定义,不幸的是它仅适用于MS Windows。 所以问题是:linux中有没有替代方法?
编辑:实际的问题是:有没有办法指示链接器仅使用第一个看到的定义并忽略任何其他定义,即使它们不同? 我知道有很多方法来定义我的数据,我不是在寻找如何定义我的数据的解决方案,相反我想知道是否有一种方法可以有多个定义并使链接器与第一个看到的一起工作。 ..
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您正在寻找“弱”gcc 属性。
I think you are looking for the 'weak' gcc attribute.
首先,您应该明确地给它一个 const 属性:
修改字符串文字会导致未定义的行为。然后至少部分地回答你的问题。
除了前面的答案中将其声明为
extern
的方法之外,第一种(不推荐)方法是声明数组static
。然后,您将在使用该数组的每个编译单元中拥有该数组的副本。只要您不想修改数组的内容(让指针指向不同的字符串),这就可以,但会稍微破坏您的代码。如果您只需要引用函数作用域中的字符串并且您有一个符合 C99 的编译器,您可以考虑使用复合文字:
然后您可以使用readonly可以预料,像
MYARRAY[1]
这样的东西和任何像样的编译器都应该能够优化这样的访问。First, you should definitively give it a
const
attribute: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 arraystatic
. 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:
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.为什么不简单地在标头中声明它,并在一个翻译单元中提供单个定义呢?
Why not simply declare it in the header, and provide a single definition in one translation unit?
如何在标头中声明为:
然后仅在一个 c 文件中定义实际的 a[]:
What about declaring in the header as:
And then define the actual a[] in only one c file: