从 C++ 代码使用的 C 内联函数

C inline function used from C++ code

我正在尝试从 C++ 代码调用用 C 定义的内联函数,但出现未解决的符号错误。我什至可以这样做吗?

在def.h中:

#ifdef __cplusplus
extern "C" {
#endif

#include "types.h"


extern inline void foo();


#ifdef __cplusplus
}
#endif /* extern "C" */

在def.c中:

inline void foo()
{
    some code
}

C++ 代码中的其他地方:

void bar()
{
    foo();
}

这是我遇到未解决的符号错误的地方。有没有办法进行编译?如果是这样,它将如何运作?编译器会用 C 定义替换我的 C++ 代码中的函数调用吗?消除功能调用很重要,因为这对于嵌入式环境而言。

谢谢。

内联 C 函数的定义应该进入 header 可见并包含在您的 C++ 代码中。

大多数编译器在源文件级别生成代码;要生成代码,编译器必须 "see" 它需要生成代码的所有函数的源代码。除非你有 LTO/LTGC,否则你必须在调用它们的每个文件中提供所有 inline 函数的源代码。

尝试将内联函数的源代码移动到相应的 header:

def.h:

#ifdef __cplusplus
extern "C" {
#endif

#include "types.h"

inline void foo()
{
   some code
}

#ifdef __cplusplus
}
#endif /* extern "C" */

def.c:

从此文件中删除 foo() 定义(或删除此文件)。

C++ 代码中的其他地方:

#include "def.h"

void bar()
{
    foo();
}