当main.c test.c 都是纯c文件编译和连接没问题正常运行
main.c
#include#include #include "test.h" int main() { show(); // printf("jshdfg"); system("pause"); }
test.c
#include#include "test.h" void show() { printf(" show executing !n"); }
test.h
#includevoid show();
运行结果
生成解决方案成功
运行成功
当main.cpp是cpp文件时
#includeusing namespace std; #include "test.h" int main() { show(); // printf("jshdfg"); system("pause"); }
编译成功 语法没错
生成解决方案出错,链接时出错
因为cpp有重载机制会把show()定义为符号 如showv (v就代表形参列表为空),但是c语言没有重载机制。所以cpp文件要使用c文件中的函数时要注明该函数在c文件中,要加上
extern "C" void show();
main.cpp改为(注意此时不用在include "test.h" 否则重定义了)
#includeusing namespace std; //include "test.h" extern "C" void show(); int main() { show(); system("pause"); }
可以正确执行了
上述规则等于告诉了编译器show()函数应该按c语言的规则来进行链接
但是每个c文件中的函数都要在main函数里
extern "C" 返回值类型 函数名(形参列表);
就太麻烦了
这种声明函数是c函数应该在.h文件中提前声明号
test.h
#ifdef __cplusplus
extern "C" {
#endif // __cplusplus
#include
void show();
//void show1()
//void show2()
//void show3()...
#ifdef __cplusplus
}
#endif // __cplusplus
这样就同时声明了多个函数是c语言函数了,#ifdef __cplusplus 在cpp文件调用时自动extern "C"
main.cpp (包含头文件即可,不用使用关键字extern了)



