C語言extern用法
1.用extern修飾變數
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void show();
void main(int *argv, char *args[]){
show();
printf("num = %d\n",num);
}
const int num = 3;
void show(){
printf("num = %d\n",num);
}
編譯出錯:
-bash-4.1$ gcc -o a Demo.c
Demo.c: 在函式‘main’中:
Demo.c:11: 錯誤:‘num’未宣告(在此函式內第一次使用)
Demo.c:11: 錯誤:(即使在一個函式內多次出現,每個未宣告的識別符號在其
Demo.c:11: 錯誤:所在的函式內也只報告一次。)
-bash-4.1$
在main函式中用extern宣告變數num,如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void show();
void main(int *argv, char *args[]){
extern const int num;
show();
printf("num = %d\n",num);
}
const int num = 3;
void show(){
printf("num = %d\n",num);
}
編譯與執行:
-bash-4.1$ gcc -o a Demo.c
-bash-4.1$ ./a
num = 3
num = 3
-bash-4.1$
這裡需要說明,宣告為extern的變數不能初始化,要另起一行賦值,如:
extern const int num;
num = 10;
當然,也可以用extern宣告一個不再同一個檔案內的全域性變數(且必須為全域性變數,如若不是則出錯,編譯不通過),如下兩個檔案:
main.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(int *argv, char *args[]){
extern const int num;
show();
printf("num = %d\n",num);
}
extern.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int num = 3;
void show(){
printf("num = %d\n",num);
}
編譯與執行:
-bash-4.1$ gcc -o a main.c extern.c
-bash-4.1$ ./a
num = 3
num = 3
-bash-4.1$
main.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main(int *argv, char *args[]){
extern const int num;
extern void show();
show();
printf("main: num = %d\n",num);
}
extern.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
const int num = 3;
void show(){
printf("show: num = %d\n",num);
}
編譯與執行:
-bash-4.1$ gcc -o a Demo.c extern.c
-bash-4.1$ ./a
show: num = 3
main: num = 3
-bash-4.1$
3.extern "C"{}修飾
此外,extern修飾符可用於指示C或者C++函式的呼叫規範。比如在C++中呼叫C庫函式,就需要在C++程式中用extern “C”宣告要引用的函式。這是給連結器用的,告訴連結器在連結的時候用C函式規範來連結。主要原因是C++和C程式編譯完成後在目的碼中命名規則不同(http://blog.sina.com.cn/s/blog_52deb9d50100ml6y.html)。
相關文章
- C語言:extern用法C語言
- c語言extern的用法C語言
- C語言中extern的用法C語言
- extern "c" 用法解析
- extern "C"的用法解析
- C語言外部變數externC語言變數
- extern用法詳解
- C語言巨集中"#"和"##"的用法C語言
- C語言函式sscanf()的用法C語言函式
- C語言指標用法大全C語言指標
- extern c 解析
- C語言位運算子及常見用法C語言
- C語言(C++語言)中##(兩個井號)和#(一個井號)用法[轉]C語言C++
- C語言生成隨機數函式的用法C語言隨機函式
- extern "C" __declspec(dllexport)Export
- 有關C語言的知識---巨集定義用法C語言
- C語言 C語言野指標C語言指標
- C語言---“C語言 誰與爭鋒?”C語言
- Python語言assert用法Python
- 逍遙自在學C語言 | 位運算子的基礎用法C語言
- 逍遙自在學C語言 | 位運算子&的高階用法C語言
- 逍遙自在學C語言 | 位運算子^的高階用法C語言
- C語言C語言
- 聊聊C語言/C++—程式和程式語言C語言C++
- C++中extern的使用C++
- c++基礎知識(八)C/C++中修飾符const、extern、static、volatile的用法C++
- C語言字串C語言字串
- C語言: returnC語言
- C語言(一)C語言
- C語言概述C語言
- c語言 %pC語言
- 字串(C語言)字串C語言
- C語言程式C語言
- CUDA C語言C語言
- C語言的本質(32)——C語言與彙編之C語言內聯彙編C語言
- c語言中的&的用法C語言
- C語言函式手冊:c語言庫函式大全|C語言標準函式庫|c語言常用函式查詢C語言函式
- C語言與嵌入式C語言的區別C語言