<分区>
文件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();
}