如何申报C99多文件项目的内联函数? [英] How to declare an inline function in C99 multi-file project?
问题描述
我要定义在一个项目内联函数,与C99编译。我该怎么办呢?
当我宣布在头文件中的函数,并给在.c文件的细节,定义不被其他文件被识别。当我把明确的功能在头文件中,我有一个问题,因为谁使用它的所有.o文件都有定义的副本,因此链接器给我一个多重定义错误。
I want to define an inline function in a project, compiled with c99. How can I do it? When I declare the function in a header file and give the detail in a .c file, the definition isn't recognized by other files. When I put the explicit function in a header file, I have a problem because all .o files who use it have a copy of the definition, so the linker gives me a "multiple definition" error.
我所试图做的是一样的东西:
What I am trying to do is something like:
header.h
inline void func()
{
do things...
}
lib1.c
#include "header.h"
...
lib2.c
#include "header.h"
与使用都lib1.o和一项实用lib2.o
with a utility which uses both lib1.o and lib2.o
推荐答案
不幸的是并非所有编译器完全符合以C99在这一点上,即使他们声称,他们会。
Unfortunately not all compilers are completely complying to C99 in that point even if they claim that they'd be.
这是符合的方式来做到这一点。
An conforming way to do this is
// header file. an inline declaration alone is
// not supposed to generate an external symbol
inline void toto(void) {
// do something
}
// in one .c file, force the creation of an
// external symbol
extern inline void toto(void);
新的gcc版本,例如,将正常工作这一点。
Newer versions of gcc, e.g, will work fine with that.
您可以通过定义类似
#ifdef PRETENDER
# define inlDec static
# define inlIns static
#else
# define inlDec
# define inlIns extern
#endif
// header file. an inline declaration alone is
// not supposed to generate an external symbol
inlDec inline void toto(void) {
// do something
}
// in one .c file, force the creation of an
// external symbol
inlIns inline void toto(void);
的编辑:的
与C99支持(通常选择 -std = C99
),我知道的编译器
compilers with C99 support (usually option -std=c99
) that I know of
- GCC(版本> = 4.3 IIRC)实现
正确的在线
模式 - PCC也是正确
- GGC< 4.3需要一个特殊的选项
实行正确的模式,
否则,他们用自己的模型
的结果在多个定义
符号如果你不小心 - ICC只是发出符号每个单位
如果不采取特别的照顾。但
这些符号是弱的符号,所以
它们不产生冲突。他们
只是炸毁你的code。 - opencc,AFAIR,沿用旧的gcc具体型号
- 铛不发出了
在线
函数符号可言,除非你有一个的extern
声明的和的使用函数指针在一个编译单元。 - 台泥只是忽略
在线
关键字
- gcc (versions >= 4.3 IIRC) implements
the correct
inline
model - pcc is also correct
- ggc < 4.3 needs a special option to implement the correct model, otherwise they use their own model that results in multiple defined symbols if you are not careful
- icc just emits symbols in every unit if you don't take special care. But these symbols are "weak" symbols, so they don't generate a conflict. They just blow up your code.
- opencc, AFAIR, follows the old gcc specific model
- clang doesn't emit symbols for
inline
functions at all, unless you have anextern
declaration and you use the function pointer in one compilation unit. - tcc just ignores the
inline
keyword
这篇关于如何申报C99多文件项目的内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!