簡體   English   中英

用gcc中的數組參數編譯extern“ c”代碼

[英]Compiling extern “c” code with array parameters in gcc

我試圖在C ++程序中包含一些C函數。 我在包含數組作為參數的函數聲明中遇到了一些問題。

extern "C" {
    double Test( int nVar1, double f[nVar1] ) {
        return f[nVar1-1];
    }
}

int main() {
    cout << "!!!Hello World!!!" << endl; 
    double f[2] = {1.0,2.0};
    Test(2, f);
    return 0;
 }

我收到以下錯誤

  • 未在此范圍內聲明“ f”
  • 未在此范圍內聲明“ nVar1”
  • 在']'標記之前在函數主體外部使用參數

我使用Atollic 8.0(GCC和C -std = gnu11)

任何幫助都將歡迎

謝謝

extern "C"不是用於在cpp源代碼中編譯c。 只能在cpp源/頭中使用C的ABI:修改,調用約定,異常處理...(感謝Ajay Brahmakshatriya)

通過修飾,我想說一下編譯器/鏈接器使用的函數的內部唯一名稱。 C整形實際上與c ++整形不同,因此不兼容。 要在c ++中找到C函數,您必須對編譯器/鏈接器說,該函數在其內部唯一名稱下是已知的。

extern "C"僅切換必須使用的ABI,包括用於創建內部唯一名稱的重整以及必須調用函數的方式,而不切換編譯模式。

如果您確實要編譯C代碼,則必須將代碼放入ac源文件中並分別進行編譯。 並使用extern "C"在cpp環境中聲明函數,以允許c ++代碼使用它。 函數的BUT聲明必須與c ++兼容,而double Test( int nVar1, double f[nVar1] )double Test( int nVar1, double f[nVar1] )

function.c,使用gcc -c編譯:

double Test( int nVar1, double f[] ) {
    return f[nVar1-1];
}

function.h,兼容的c和c ++:

#ifndef _FUNCTION_H
#define _FUNCTION_H

#ifdef __cplusplus
extern "C" {
#endif

double Test( int nVar1, double f[] );

#ifdef __cplusplus
}
#endif

#endif

main.cpp,使用g++ -c編譯:

#include "function.h"

int main() {
    cout << "!!!Hello World!!!" << endl; 
    double f[2] = {1.0,2.0};
    Test(2, f);
    return 0;
 }

最后,使用g ++鏈接器鏈接所有內容:

g ++ function.o main.o -o my_program

在這里查看示例:

問題在於數組大小。 它不能是變量,應該是const。 如果您需要傳遞可變大小的數組,則只需將指針傳遞給它的第一個元素即可: double Test( int nVar1, double * f) {

您建議使用g ++編譯這樣的C函數,而不必重新編寫此舊函數中包含的完整代碼的建議

#ifdef __cplusplus
extern "C" {
#endif

int ComputedF(int nPoints, int nFunc, double x[], double f[nPoints][nFunc], double df[nPoints][nFunc])

#ifdef __cplusplus
}
#endif

謝謝

暫無
暫無

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

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