簡體   English   中英

有沒有辦法在使用extern'C'后重新啟用名稱修改?

[英]Is there a way to re-enable name mangling after using extern 'C'?

可以說我有一個c ++頭文件,如下所示:

/* cpp_header.h */
#include <vector>

#ifdef __cplusplus
extern 'C' {
#endif
void foo1(int x);
void foo2(int y);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
/* function I don't want visible to C compiler */
void foo3(vector<int> &v);
#endif

現在我將此頭文件包含在C頭文件中:

/* c_header.h - all implementation built with C compiler */
#include <stdio.h>
#include "cpp_header.h"

int cfoo();
int cfoo1(int x);

現在讓我說我想在另一個cpp文件中使用cfoo()和cfoo1(),我這樣做:

/* crazy.cpp - this will cause a build breakage */
extern 'C' {
#include "c_header.h"
}
#include <iostream>

int main() {
   cfoo();
   cfoo1(88);
   std::cout << "Yes, this is crazy!" << std::endl;
   return 0;
}

上面的代碼永遠不會構建,因為第一個頭文件中的'foo3()'會抱怨我們正在嘗試使用C-linkage構建模板。 發生這種情況是因為我們將整個c_header.h文件包裝在'extern C'防護中。 有沒有辦法可以添加一些可以反轉'extern C'保護的東西,這樣就可以用C ++鏈接構建foo3。 也許是這樣的:

#ifdef __cplusplus
extern 'CPP' {  /* re-enable C++ name-mangling/linkage */
   foo3(vector<int> &v);
}

謝謝。

https://en.cppreference.com/w/cpp/language/language_linkage中所述 ,您可以使用extern "C"extern "C++" (后者是C ++的默認值)。

它還說

當語言規范嵌套時,最內層的規范是有效的規范。

所以

extern "C" {
    extern "C++" void foo3(vector<int> &v);
}

應該工作正常。

也就是說,更好的解決方案是將#ifdef __cplusplus / extern "C" {部分添加到C頭本身的聲明中。 然后您不需要將#include包裝在主cpp文件中。

如:

/* c_header.h - all implementation built with C compiler */
#include <stdio.h>
#include "cpp_header.h"

#ifdef __cplusplus
extern "C" {
#endif
int cfoo();
int cfoo1(int x);
#ifdef __cplusplus
}
#endif

然后所有消費者都可以#include "c_header.h" ,無論他們是在C ++還是C.

暫無
暫無

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

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