【发布时间】: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();
}
【问题讨论】:
-
extern "C"是 C++ 功能:en.cppreference.com/w/cpp/language/language_linkage