我正在嘗試將一些用C編寫的函數包含到C++項目中。我遵循these的說明進行了很多工作。 不幸的是,我不需要調用的所有C函數都在c頭文件中聲明。有些只是在「.c-files」中定義的靜態函數。如何將C函數導入尚未在C頭中聲明的C++項目中?
有沒有辦法仍然稱這樣從我的類C++項目的內部「未宣佈的-C函數」,而不改變碳源(未通過自己維護)?
我已經想過向前聲明C函數自己在我的C++頭是這樣的:
extern "C"
{
#include "c_header_1.h"
static void c_function(int* out, const unsigned char len, const some_c_struct* st);
#include "c_header_2.h
}
GCC只報告了一個錯誤:
warning: void c_function(int*, const unsigned char, const some_c_struct*); declared static but never defined [-Wunused-function].
的指針結構作爲第三個參數來傳遞c_function(int*, const unsigned char, const some_c_struct*)
似乎使事情更棘手,因爲這種類型的some_c_struct
是屬於c_function(...)
被宣佈爲好「的.c文件」標題中聲明。這意味着我需要在c_function(...)
的前向聲明之前包含標題,但顯然這會使鏈接器監督定義。
A中的C++代碼的非常simplyfied版本看起來大致是這樣的: 頭文件 「CppClass.h」:
#ifndef CPP_CLASS_H
#define CPP_CLASS_H
extern "C"
{
#include "c_header_1.h"
#include "c_header_2.h"
...
}
class CppClass
{
public:
//...
void some_member();
//...
};
#endif
實施 「CppClass.cpp」
//...
void CppClass::some_member()
{
//...
::c_func_x(32, &data); // call to function in c_header_1
//...
::c_func_y(&data2); // call to function in c_header_2
::c_function(data3, len, st);
}
'static'功能都在內部他們所定義的模塊,你不能從外部接觸他們。 – melpomene
@melpomene沒錯。如果它不應該從C調用(這可能是爲什麼它是'靜態'),爲什麼它應該從C++調用?並且:你永遠不會在C頭文件中放置一個'static'。這是無稽之談。 – tofro
除非你計劃'#include'.c文件到你的翻譯單元(yuck),而不* *在這個範例之外編譯它們,那些'static'函數並不存在。關於cpp文件。但是,從你的具體情況來看,這是一個可怕的選擇。 – WhozCraig