extern "C" 导致错误 "expected '(' before string constant"

jtr*_*tro 3 c c++ extern

文件1.c

int add(int a, int b)
{
  return (a+b);
}
Run Code Online (Sandbox Code Playgroud)

文件2.cpp

void main()
{
    int c;

    c = add(1,2);
}
Run Code Online (Sandbox Code Playgroud)

h1.h

extern "C"  {

#include "stdio.h"

int add(int a,int b);
}
Run Code Online (Sandbox Code Playgroud)

情况 1:当我在file1.c文件中包含h1.h 时,gcc 编译器会抛出错误“ expected '(' before string constant ”。

案例2:当我在file2.cpp文件中包含h1.h时编译工作成功

题:

1)这是否意味着我不能在C中包含带有extern“C”函数的头文件??

2) 我可以在 extern"C" 中包含标题,如下所示

extern "C" {

#include "abc.h"
#include "...h"
}
Run Code Online (Sandbox Code Playgroud)

3) 我可以将 C++ 函数定义放在带有 extern "C" 的头文件中,以便我可以在 C 文件中调用它吗?

例如

a.cpp(cpp 文件)

void test()
{
   std::printf("this is a test function");
}
Run Code Online (Sandbox Code Playgroud)

啊(头文件)

extern "C" {
void test();
}
Run Code Online (Sandbox Code Playgroud)

b_c.c(c 文件)

#include "a.h"

void main()
{
  test();
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*szL 10

像这样写啊:

#pragma once
#ifdef __cplusplus
extern "C"
{
#endif

int add(int a,int b);

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以声明多个函数 - 无需为每个函数添加 extern C 前缀。正如其他人所提到的:extern C 是 C++ 的东西,因此当被 C 编译器看到时,它需要“消失”。


And*_*rsK 2

由于 C 编译器无法理解 extern "C",因此您需要创建一个可以包含在 C 和 C++ 文件中的标头。

例如

#ifdef __cplusplus
extern "C" int foo(int,int);
#else
int foo(int,int);
#endif
Run Code Online (Sandbox Code Playgroud)