C++中extern "C"块的应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/89737948

一 点睛

经常能在C和C++混编代码的程序中看到这样的语句:

#ifdef __cplusplus   //plus是+的意思,这里是c++的意思
    extern "C"{
#endif
    ...
#ifdef __cplusplus
    }
#endif

其中cplusplus是C++的预定义宏,表示当前开发环境是C++。在C++语言中,为了支持重载机制,在编译生成汇编代码中,会对函数名进行一些处理(通常称为函数名字改编),如加入函数的参数类型或返回类型,而在C语言中,只是简单的函数名字而已,并不加入其它信息,如下所示:

int func(int demo);
int func(double demo);

C语言无法区分上面两个函数的不同,因为C编译器产生的函数名都是_func,而C++编译器产生的名字则可能是_func_Fi和_func_Fd,这样就很好把函数区分开了。

所有,在C和C++混编的环境下,extern "C"块的作用就是告诉C++编译器这段代码要按照C标准编译,以尽可能地保持C++与C的兼容性。

二 __cplusplus的使用方法

1 代码

#include<stdio.h>
int main() {
    #define TO_LITERAL(text) TO_LITERAL_(text)
    #define TO_LITERAL_(text) #text                    
    #ifndef __cplusplus
    /* this translation unit is being treated as a C one */
        printf("a C program\n");
    #else
       /*this translation unit is being treated as a C++ one*/
        printf("a C++ program\n__cplusplus expands to \""
          TO_LITERAL(__cplusplus) "\"\n");
    #endif
    return 0;
}

2 运行

[root@localhost charpter01]# g++ 0120.cpp -o 0120
[root@localhost charpter01]# ./0120
a C++ program
__cplusplus expands to "199711L"

3 说明

#define TO_LITERAL_(text) #text中的第2个#号表示:把一个符号直接转换为字符串

如果没有定义__cplusplus,那么当前源代码就会当做C源代码处理,如果定义了__cplusplus,那么当前源代码被当做C++源代码处理,并且输出__cplusplus宏被展开后的字符串。

我们把该程序的后缀改为.c,并用gcc方式编译,结果如下:

[root@localhost charpter01]# cp 0120.cpp 0120.c
[root@localhost charpter01]# gcc 0120.c -o 0120
[root@localhost charpter01]# ./0120
a C program

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/89737948