本文介绍了如何在 C99 多文件项目中声明内联函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在项目中定义一个内联函数,用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.

我想做的是这样的:

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.

一种符合要求的方法是

// header file. an inline definition 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.

你可以通过定义类似的东西来为其他编译器(伪装者)摆脱它

You may get away with it for other compilers (pretenders) by defining something like

#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)实现正确的 inline 模型
  • pcc 也是正确的
  • ggc <4.3 需要一个特殊的选项来实施正确的模型,否则他们使用自己的模型这导致多个定义不小心的符号
  • icc 只是在每个单元中发出符号如果你不特别注意.但这些符号是弱"符号,所以它们不会产生冲突.他们只是炸毁你的代码.
  • opencc,AFAIR,遵循旧的 gcc 特定模型
  • clang 根本不会为 inline 函数发出符号,除非你有一个 extern 声明 并且 你在一个函数中使用了函数指针编译单元.
  • tcc 只是忽略 inline 关键字
  • gcc (versions >= 4.3 IIRC) implementsthe correct inline model
  • pcc is also correct
  • ggc < 4.3 needs a special option toimplement the correct model,otherwise they use their own modelthat results in multiple definedsymbols if you are not careful
  • icc just emits symbols in every unitif you don't take special care. Butthese symbols are "weak" symbols, sothey don't generate a conflict. Theyjust 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 an extern declaration and you use the function pointer in one compilation unit.
  • tcc just ignores the inline keyword

这篇关于如何在 C99 多文件项目中声明内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:04