命名空间中的inline函数在gcc上链接期间生成重复的符号 [英] inline function in namespace generate duplicate symbols during link on gcc

查看:246
本文介绍了命名空间中的inline函数在gcc上链接期间生成重复的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命名空间与inline函数,如果几个源文件将被使用。
当尝试链接我的应用程序时,内联函数报告为重复的符号。
好​​像我的代码只是不内联函数,我想知道这是否是预期的行为和如何最好地处理它。

I have a namespace with inline function that will be used if several source files. When trying to link my application, the inline function are reported as duplicate symbols. It seems as if my code would simply not inline the functions and I was wondering if this is the expected behavior and how to best deal with it.

我使用以下gcc选项:
-g -Wextra -pedantic -Wmissing-field-initializers -Wredundant-decls -Wfloat-equal -Wno-reorder -Wno-long-long
同样的代码样式似乎

I use the following gcc options: -g -Wextra -pedantic -Wmissing-field-initializers -Wredundant-decls -Wfloat-equal -Wno-reorder -Wno-long-long The same code style seems to compile and link properly when build in a VC7 environment.

以下代码示例显示了代码的结构:

The following code example shows the structure of the code:

/* header.h */
namespace myNamespace {
inline bool myFunction() {return true;}
}

/* use_1.cpp */
#include "header.h"
...
bool OK = myNamespace::myFunction();
...

/* use_2.cpp */
#include "header.h"
...
bool OK = myNamespace::myFunction();
...


推荐答案

只能作为编译器的提示。如果编译器决定函数在没有inline的情况下表现更好,它不会内联它。有一些供应商特定的关键字使编译器内联一个函数 - 它是 __ attribute __((always_inline))为GCC和 __ forceinline 对于Visual C ++。


如果你真的想确保你的函数不会导致链接器错误在所有情况下在所有标准编译器,你可能想要使它模板化,因为模板函数保证不会导致链接器错误,即使在头文件中定义。但是,对于非常简单的功能,这是没有必要的。

The inline keyword is taken only as a hint by the compiler. If the compiler decides that the function would be better performing without inline, it will not inline it. There are vendor-specific keywords that make the compiler inline a function - it is __attribute__((always_inline)) for GCC and __forceinline for Visual C++.

If you really want to make sure your function won't be causing linker errors in all cases on all standard compilers, you might want to make it templated, as templated functions are guaranteed not to cause linker errors even if defined in headers. This is, however, quite unnecessary for really simple functions.

这篇关于命名空间中的inline函数在gcc上链接期间生成重复的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆