c++ - 外部 "C"导致错误 "expected ' (' before string constant"

标签 c++ c extern

<分区>

文件1.c

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

文件2.cpp

void main()
{
    int c;

    c = add(1,2);
}

h1.h

extern "C"  {

#include "stdio.h"

int add(int a,int b);
}

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

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

问题:

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

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

extern "C" {

#include "abc.h"
#include "...h"
}

3) 我可以用 extern "C"将 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();
}

最佳答案

像这样写a.h:

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

int add(int a,int b);

#ifdef __cplusplus
}
#endif

这样你就可以声明多个函数——不需要为每个函数都加上 extern C 前缀。 正如其他人提到的:extern C 是 C++ 的东西,因此当 C 编译器看到它时它需要“消失”。

关于c++ - 外部 "C"导致错误 "expected ' (' before string constant",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43602910/

相关文章:

c++ - 如何从 C++ 验证 Lua 表键

c++ - 字符数组 *

c - 解密 x86 汇编函数

c - 多次应用模糊算法

c - 用户在窗口外单击时如何隐藏 Gtk 弹出窗口

c - 重定位被截断以适应 : R_X86_64_32

c++ - C/C++ 中存储值 <=10^20 的数据类型

c++ - googletest 中的参数化和共享资源测试

compiler-construction - 如何链接两个nasm源文件

c++ - C++ 中的这些 extern 声明有什么区别?