extern 用法:
1.readme:extern 表明是“外部的” 与 static 相反,需要引用另一个文件中定义的 variable or function ,
需要在调用之前 extern 声明它的存在。 一般都是在.h文件中声明。
2.注意:
在.h 文件中 variable 需要添加 extern,function 可以添加,也可以不添加 extern,.h文件中的function 默认是 extern 的。
这是便于区分 声明 与 定义的 区别。 如果你一不小心在.h 定义了一个 variable ,每个文件都有 一个variable,这并非你的本意吧。
static variable 应该定义在 source file中,不应该在 .h中。
3.extern "C"
这个是在 c++调用c时候出现,因为c++支持函数重载【利用名字粉碎机制】,所以c编译器与c++编译器生成的库文件以及.o文件
函数名称形式不同,以至于连接出错。
**example:**
makefile:
gcc -c c_fun.c -o c_fun.o
g++ -c cpp_fun.cpp -o cpp_fun.o
g++ cpp_fun.o c_fun.o
file:cpp_fun.h
#ifndef __CPP_FUN_H
#define __CPP_FUN_H
int get_a(void);
#ifdef __cplusplus
extern "C"{
#endif
void add(int a,int b);
#ifdef __cplusplus
}
#endif
#endif
file:c_fun.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void add(int a,int b)
{
printf("a+b=%d\n",a+b);
return;
}
file:cpp_fun.cpp
#include <iostream>
#include <string>
#include "cpp_fun.h"
#include "cpp_fun.h"
using namespace std;
int a=7;
int get_a(void)
{
return a;
}
int main(int argc,char *argv[])
{
add(get_a(),10);
return 0;
}