c在c ++实践中

The*_*eAJ 1 c c++

我通常不会这样做,但我正在处理的项目需要一些交流源文件中的函数.

extern "C" {
    int words(char sentence[]);
    int match(char str[], char sentence[], int n);
}
Run Code Online (Sandbox Code Playgroud)

我只是想知道,将这些原型添加到c中的链接函数的最佳位置在哪里?

它应该添加到c ++源文件(在我的情况下,command.cpp)还是c/c ++标题?(command.h)

pmd*_*mdj 5

在最不容易出错的办法是把声明在一个共享的C&C++头文件,并且#ifdefextern "C" {仅由C++编译器(它是在C语言的语法错误)可以使用:

#ifdef __cplusplus
extern "C" {
#endif
  int words(char sentence[]);
  int match(char str[], char sentence[], int n);
#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

我个人也喜欢这种预定义的变体,为未定义的extern语法定义一个宏:

#ifdef __cplusplus
#define CFUN extern "C"
#else
#define CFUN
#endif

CFUN int words(char sentence[]);
CFUN int match(char str[], char sentence[], int n);
Run Code Online (Sandbox Code Playgroud)

这使得凌乱的#ifdef内容本地化.您可以将它放在一个项目范围的头文件中,并在CFUN任何地方使用说明符.如果CFUN宏可能与现有定义发生冲突,您可能希望为宏的名称添加前缀.