【问题标题】:extern "C" causing an error "expected '(' before string constant" [duplicate]extern“C”导致错误“预期'('在字符串常量之前”[重复]
【发布时间】:2017-09-22 00:14:09
【问题描述】:

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 编译器会抛出错误“expected '(' before string constant”。

案例 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();
}

【问题讨论】:

标签: c++ c extern


【解决方案1】:

这样写 a.h:

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

int add(int a,int b);

#ifdef __cplusplus
}
#endif

这样您可以声明多个函数 - 无需在每个函数前面加上 extern C。 正如其他人提到的:extern C 是 C++ 的东西,所以它需要在 C 编译器看到时“消失”。

【讨论】:

    【解决方案2】:

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

    例如

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

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多