C++由于支持函数函数重载,因此函数被编译后与C语言的函数被编译后的命名规则不一样,C直接调用C++函数,链接时无法找到C++函数:
//f.cpp
#include <iostream>
#include "f.h"
using namespace std;
class A{
public:
A(int d):m_data(d)
{}
void pOut()
{
cout<<"m_data is "<<m_data<<endl;
}
private:
int m_data;
};
void func()
{
A a(10);
a.pOut();
}
//f.h
void func();
//m.c
#include "f.h"
int main()
{
func();
return 0;
}
编译报错:
m.c:4: undefined reference to `func'
解决此问题,需要在声明接口函数时使用extern “C”进行声明
//f.h
#ifdef __cplusplus
extern "C" {
#endif
void func();
#ifdef _

C++支持函数重载,导致C直接调用C++函数时出现链接错误。为解决这个问题,需要在C++的接口函数声明中使用`extern "C"`。这样可以确保C++编译器以C的方式处理函数,避免命名冲突。C++调用C语言函数则无此问题。
订阅专栏 解锁全文

3955

被折叠的 条评论
为什么被折叠?



