bug記錄——C語言調用C++函數接口

結論

當C語言 需要調用C++函數接口(比如func.h,func.cpp)時,func.h中不能出現c++特有的class定義或頭文件包含。即:關於class的定義或含有class的頭文件包含必須放在源文件中(如func.cpp中),不能放在頭文件(func.h,無論是extern “C” 裏還是exter "C"外)中

一個小bug卡了好多天。。特此記錄。。。

證明

main.c代碼如下:

#include <stdio.h>
#include "func.h"
typedef  unsigned char   UINT8;

int main(){
	
	printf("result=%d\n",add(2,3,2));
	printf("result=%d\n", add(2, 3,1));
	char buf[] = "hello";
		
	printf("%d\n",str(buf));
	UINT8 payload[100];
	refillDataForTteEnd( payload);
	system("pause");
	return 0;
}

func.h代碼如下:

#ifndef __FUNC__
#define __FUNC__

//class A{   //class A的定義放在func.h中編譯會報錯(無論放在extern "C"之外還是extern "C"之內都彙報錯),放在func.cpp中可以正常。包含含有class定義的頭文件同理。
//public:
//	int a;
//};
#ifdef __cplusplus             //告訴編譯器,這部分代碼按C語言的格式進行編譯,而不是C++的
extern "C"{
#endif
	
	int  add(int a, int b, int flag);
	int str(char* buf);
	typedef  unsigned char   UINT8;
	void refillDataForTteEnd(UINT8* payload);
#ifdef __cplusplus
}

#endif

#endif


func.cpp代碼如下:
```cpp
#include <iostream>
#include "func.h"
#include "overload.h"

class A{
public:
	int a;
};
int  add(int a, int b,int flag){
	std::cout << "int add()" << std::endl;
	std::cout << __cplusplus << std::endl;
	A h;
	h.a = 23;
	std::cout << "h,a = " << h.a << std::endl;
	if (flag == 1){
		return addnum(a, b);
	}
	else{
		return addnum(a, b, flag);
	}


}

int str(char* buf){
	return strlen(buf);

}

void refillDataForTteEnd(UINT8* payload) {
	A h;
	h.a = 23;
	std::cout << "refillDataForTteEnd " << h.a << std::endl;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章