簡體   English   中英

從.c文件中調用.cpp文件中的函數

[英]Calling a function in a .cpp file from a .c file

我一直在努力解決我正在研究的項目的問題。 讓我們假設我有幾個文件:

reflection.h 
sll_insert.c
record_sll.c
io_recorder.cpp

所有上面提到的cpp和c文件都使用:

#include "reflection.h"

"reflection.h"中有以下聲明:

extern void io_recorder_fun_entry(char * name, TypedObject args[], int len);

extern void io_recorder_fun_exit(char * name, TypedObject args[], int len);

這兩個函數在"io_recorder.cpp"中實現,它們使用名為io_record "io_recorder.cpp"另一個函數。

現在,在"io_recorder.cpp" ,兩個函數如下:

extern "C" void io_recorder_fun_entry(char * name, TypedObject args[], int len) {
    cout << "Entering function "<< name << endl; 
    io_record(args, len);
}

extern "C" void io_recorder_fun_exit(char * name, TypedObject args[], int len) {
    cout << "Exiting function "<< name << endl; 
    io_record(args, len);

}

當在io_record, there are calls being made to several functions declared in reflection.h and implemented in “record_sll.c”中io_record, there are calls being made to several functions declared in reflection.h and implemented in

我有兩個問題:

  1. 在這種情況下,C和C ++之間的連接對我來說不起作用(我之前已經使用其他文件進行了實驗,之前它似乎有用)。 在嘗試編譯時,我收到如下錯誤:

    io_recorder.cpp: In function 'void io_recorder_fun_entry(char*, TypedObject*, int)':

    io_recorder.cpp:61:79: error: conflicting declaration of 'void io_recorder_fun_entry(char*, TypedObject*, int)' with 'C' linkage tern "C" void io_recorder_fun_entry(char * name, TypedObject args[], int len) {

    io_recorder.cpp:4:0: reflection.h:32:13: note: previous declaration with 'C++' linkage extern void io_recorder_fun_entry(char * name, TypedObject args[], int len);包含的文件中io_recorder.cpp:4:0: reflection.h:32:13: note: previous declaration with 'C++' linkage extern void io_recorder_fun_entry(char * name, TypedObject args[], int len);

顯然我做錯了什么,我無法弄清楚是什么。 為了正確編譯,我應該改變什么?

  1. 在以前的錯誤,似乎io_record沒有從識別功能record_sll當我用他們。 它與問題1中的錯誤有什么關系嗎? 如果沒有,我該怎么做才能確保io_record知道它們。

在此先感謝您的幫助,我希望我能盡快解決這個問題。

從C ++的角度來看 ,您的定義存在沖突:

  • 在您的標題中,您將兩個函數聲明為普通的c ++函數(即沒有特定的調用約定)
  • 在正文中,您可以使用C調用約定來定義函數

這是一個問題,因為在使用標頭的所有編譯單元中,編譯器將使用c ++調用序列生成代碼,而不知道您的函數體使用另一個調用序列。 因此錯誤消息。

要解決此問題,必須將兩種情況下的函數聲明為extern "C"

然而, 從C的角度來看 ,不識別extern "C"語法。 因此,如果您想為C ++和C使用相同的標頭,則需要一些帶有條件編譯的額外健身房:

#ifdef __cplusplus
extern "C" {  // this line will be compiled only if included in a .cpp file and not in a .c
#endif
    // your c function declaration go here without the extern "C"
#ifdef __cplusplus
}
#endif

您可以在此常見問題解答頁面上找到有關混合C和C ++的其他信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM