博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

extern用法总结

Posted on 2012-08-18 11:08  开源云  阅读(722)  评论(0编辑  收藏  举报

一、extern "C"讲解

extern "C"是使C++能够调用C写作的库文件的一个手段,如果要对编译器提示使用C的方式来处理函数的话,那么就要使用extern "C"来说明。__cplusplus是cpp中的自定义宏,那么定义了这个宏的话表示这是一段cpp的代码。

main.cpp

extern void f1();

int main()
{
    f1();
    return 0;
}

a.cpp

#include <stdio.h>

void f1()
{
    printf("test\n");
}

makefile

all:
    g++ -o base.o -c base.cpp
    g++ -o main.o -c main.cpp
    g++ -o test main.o base.o

用UE打开base.o,可以看到base.cpp _Z2f1v puts __gxx_personality_v0,此时编译器将函数定义为_Z2f1v。

我们再对代码进行修改,将f1()函数的定义用extern "C"定义成c函数,在main中要引用的话,我们就需要加入extern "C"来声明f1()函数。

main.cpp

#ifdef __cplusplus
extern "C" {
#endif

extern void f1();

#ifdef __cplusplus
}
#endif

int main()
{
    f1();
    return 0;
}

a.cpp

#include <stdio.h>

extern "C"
{
void f1()
{
    printf("test\n");
}
}

此时再次查看base.o,将看到base.cpp f1 puts __gxx_personality_v0,编译器将其编译为c函数f1。

如果我们将main.cpp中的extern "C"去掉呢?再次编译,将会报main.cpp:(.text+0x12): undefined reference to `f1()',找不到f1()的定义。因为这时候编译器会去寻找函数名为_Z2f1v的c++定义。

是不是对extern "C"有了一个新的认识呢。在编写c++代码的时候,我们经常要调用一些以前写过的c库,所以在调用的时候,一定要记住使用extern "C"来声明函数。否则会编译不过的哦。

二、extern用法

对于c

1、函数名之前加extern作用是声明该函数,可能在别的源文件中定义。其实不使用extern效果是一样的。

2、extern修饰变量时,表明该变量在别处定义过了,这里将使用那个变量。

对于c++

1、养成良好的编程习惯,变量的定义放在cpp中。这样只需要引用.h就完成了变量的声明啦。我在写c++代码的时候真的好少用extern。

2、对于c库一定要记得使用extern "C"