簡體   English   中英

在Visual Studio 2010中作為C代碼編譯

[英]Compile as C code in Visual Studio 2010

我正在編寫一些C代碼以與硬件連接。 該硬件具有內置的API函數,這些函數在頭文件中定義,並包含在外部“ C”塊中。 由於某些原因,當我在屬性表中選擇“編譯為C代碼”時,無法使程序編譯。 甚至更陌生,當我“作為C ++編譯”時,我也不會得到任何錯誤,不更改任何代碼,然后將其更改回“作為C編譯”。 到底是怎么回事? 我僅有的兩個文件是main.c,header_file.h和define_file.h(在header_file.h中為#include d)。

我編寫了一個非常簡單的程序來說明正在發生的事情:

#include "header_file.h"

int main(){
  return 0;
}

為了提供更多細節,我得到的錯誤來自頭文件,它看起來像:

#ifdef __cplusplus
extern "C" {
#endif

#include defines_file.h

FUNC_API(int) Function(Type1 var1, Enum2 var2, Type3 var3, void* ptr=0);

#ifdef __cplusplus
}
#endif

define_file.h看起來像:

enum Enum2{
//enumerator list
};

錯誤是:

1>c:\header_file\include\header_file.h(78): error C2146: syntax error : missing ')' before identifier 'var2'
1>c:\header_file\include\header_file.h(78): error C2081: 'Enum2' : name in formal parameter list illegal
1>c:\header_file\include\header_file.h(78): error C2061: syntax error : identifier 'var2'
1>c:\header_file\include\header_file.h(78): error C2059: syntax error : ';'
1>c:\header_file\include\header_file.h(78): error C2059: syntax error : ','
1>c:\header_file\include\header_file.h(78): error C2059: syntax error : ')'

似乎在考慮Enum2Type1的變量名。 好像我缺少Enum2定義,但我沒有-它在define_file.h中定義。 我注意到的一件事是Enum2沒有在“ extern C”塊內定義。 那是問題嗎? 我不想更改頭文件,因為我沒有寫它們。 (我仍不確定100%“外部C”如何工作。)

聲明為extern "C"的接口本身必須是有效的C; 所以界面:

  • 可能不是班級成員
  • 可能不會超載
  • 可能不涉及課程類型
  • 可能沒有可選參數
  • 在語法上必須作為C代碼有效。

只要POD結構本身在C ++編譯中聲明為extern“ C”,就可以使用。 在C語言中,與C ++ struct不同,枚舉和聯合標記不是位於自己的類型名稱上,因此必須進行顯式限定,或者定義為typedef別名。

請注意以下幾點:

#if defined __cplusplus
extern "C"
{
#endif
    // Declarations must be valid C syntax
    int function() ;
#if defined __cplusplus
}
#endif

解析為:

extern "C"
{
    // Declarations must be valid C syntax
    int function() ;  
}

在C ++中,只是:

    // Declarations must be valid C syntax
    int function() ;  

在C

重要的一點是,當編譯為C代碼時,不得包含C ++專有的內容。

extern "C"是C ++語法,用於切換支持重載,類成員關系和可選參數等所必需的所有符號名改寫,並且無效C。它強制C ++編譯中的符號名與在C編譯中。

在C語言中,您需要將枚舉定義為類型,或者在像類型名稱一樣使用時,在其前面加上單詞enum

因此,您需要修改定義

//replace this:
enum Enum2{A,B,C,D};

//with this
typedef enum{A,B,C,D} Enum2;

或者您可以保持定義相同,然后將函數簽名更改為

FUNC_API(int) Function(Type1 var1, enum Enum2 var2, Type3 var3, void* ptr);

事實是C和C ++是兩種截然不同的語言,如果標頭不是在編寫時考慮這兩種語言中的一種,那么就不能在不進行修改的情況下使用它。

編輯 :正如@Clifford提到的, struct類型也是如此。

struct Type1  //this is passed as "struct Type1 pName"
{
    int a,b,c;
};

typedef struct //this is passed as "Type2 pName"
{
    int a,b,c;
}Type2;

//this is passed as either "struct type3 pName" or "type3_t pName"
typedef struct type3
{
    int a,b,c;
}type3_t;

暫無
暫無

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

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