如果我们需要引用一个外部库里面的变量或函数,要涉及到extern,具体该怎么写呢?
下面是一小段例子函数:假设我们有2个源文件hello.h和hello.cpp
hello.h的代码如下
#ifdef __cplusplus
extern "C" {
#endif
extern const char g_test[3];
#ifdef __cplusplus
}
#endif
hello.cpp的代码如下
extern const char g_test[] = {
'a', 'b', 'c'
};
第三方有个main.cpp,源码如下
#include <stdio.h>
#include "hello.h"
int main()
{
printf("First char is:%c\n", g_test[0]);
return 0;
}
编译
g++ -o hello.cpp.o -c hello.cpp
g++ -o main.cpp.o -c main.cpp
g++ hello.cpp.o main.cpp.o -o Hello
运行输出:
First char is:a
这样是正确的,可以运行。
有几个问题:1.extern在语法书上都是表示:声明一个变量,不分配内存空间,那么hello.h和hello.cpp中用的都是extern,mian.cpp中也没有定义,是在哪里分配的内存呢?
原因:大部分书上在讲extern的时候都是这么讲的,实际上加上extern确实是声明,但是如果变量后面还有赋值操作,例如:extern int i = 0;
那么这个就是声明 + 定义了,注意:为什么不是简单的定义呢?即 extern int i = 0; 不等价于 int i = 0;
这是因为C/C++有三种linkage方式:1.extern linkage 2.internal linkage 3.none linkage, 对于全局变量,不加extern,默认则是internal,所以上面二者是不等价的,如果需要外部链接,必须加extern。
C/C++有两种link object,extern object(函数外的声明)和internal object(函数内的声明)
下面是这三种方式的可见范围
Type of linkage | Type of object | Accessibility |
external | external | throughout the program |
internal | external | a single file |
none | internal | local to a single function |