C語言extern用法

Koma_Wong發表於2017-11-22

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$ 


2.用extern修飾函式

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)。








相關文章