"extern "C"" 引起错误 "expected '(' before string constant"。

11 浏览
0 Comments

"extern "C"" 引起错误 "expected '(' before string constant"。

这个问题在这里已经有了答案:

什么是在C ++中使用extern \"C\"的作用?

如何在C++程序中包含C头文件?

file1.c

int add(int a, int b)
{
  return (a+b);
}

file2.cpp

void main()
{
    int c;
    c = add(1,2);
}

h1.h

extern "C"  {
#include "stdio.h"
int add(int a,int b);
}

情况1:

当我在file1.c文件中包含h1.h时,gcc编译器会抛出一个错误“在字符串常量之前需要\'(\'”。

情况2:

当我在file2.cpp文件中包含h1.h时,编译工作成功。

问题:

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

2)我可以像下面展示的那样在extern“C”中包含头文件吗?

extern "C" {
#include "abc.h"
#include "...h"
}

3)我可以将C ++函数定义放在extern“C”头文件中,以便在C文件中调用吗?

例如

a.cpp(cpp文件)

void test()
{
   std::printf("this is a test function");
}

a.h(头文件)

extern "C" {
void test();
}

b_c.c(c文件)

#include "a.h"
void main()
{
  test();
}

admin 更改状态以发布 2023年5月21日
0
0 Comments

由于使用了extern "C"语法,C编译器无法正常理解,因此需要创建一个头文件,使其可以被C和C++文件同时引用。

例如:

#ifdef __cplusplus
extern "C" int foo(int,int);
#else
int foo(int,int);
#endif

0
0 Comments

编写a.h文件,如下所示:

#pragma once
#ifdef __cplusplus
extern "C"
{
#endif
int add(int a,int b);
#ifdef __cplusplus
}
#endif

这样你就可以声明多个函数——不需要在每个函数前面加上extern C。正如其他人提到的:extern C是C++的事情,因此在C编译器中需要“消失”。

0