關於extern的最新總結

2021-08-30 18:51:09 字數 2507 閱讀 5397

最近看了些extern的用法,現做了一些總結如下。

1. 呼叫 .c 檔案 中的全域性變數和方法

// common.c

#include int num = 100;

char *msg = null;

void print(const char *msg)

// main.c

#include extern int num;

extern char *msg;

extern void print(const char *msg);

int main(void)

// makefile

all: main

common.o: common.c

gcc -c common.c

main.o: main.c

gcc -c main.c

main: main.o common.o

gcc main.o common.o -o main

2. .h 檔案 中宣告變數和方法  .c 檔案 中定義對應的變數和方法

// common.h

#ifndef _common_h

#define _common_h

#include // 標頭檔案中的extern 表示此處宣告的變數會在別的檔案中給出定義

extern int num;

extern char *msg;

// 標頭檔案中對方法的extern修飾可以省略,因為:functions are declared extern by default

extern void print(const char *msg);

#endif

// common.c

#include "./common.h"

// 此處對變數進行定義

int num = 100;

char *msg = null;

// 對方法進行定義

void print(const char *msg)

// main.c

#include "./common.h"

// 宣告以下變數和方法可能是在別的檔案(模組)中定義的

extern int num;

extern char *msg;

extern void print(const char *msg);

int main(void)

// makefile

all: main

common.o: common.c common.h

gcc -c common.c

main.o: main.c common.h

gcc -c main.c

main: main.o common.o

gcc main.o common.o -o main

3. 如果 c++**中不呼叫c的變數或者方法,則用法同c

4. c++中呼叫c的變數,用法同 c(即只需要在呼叫處用extern宣告下該變數就行了)

5. c++中呼叫c的方法,此處就關係到c&c++中對於方法名的不同compile方法。因為c++是支援過載的,而c不支援。那麼在編譯時,對方法名的處理方法兩者不相同。

比如同樣乙個方法 void func(int);

c 編譯後可能是 func_

而c++要考慮倒其對方法的過載,那麼該方法名在編譯後就可能是 func_int_

因此,在c++中要呼叫 用c寫出的方法,那麼就要使用倒 extern 「c」

#ifdef __cplusplus

extern 「c」

#endif

注意:c++呼叫c中的變數不可在此**塊中宣告,應該和普通的一樣。直接

extern int ***; 即可

// common.c

#include #include int stdafxii = 10;

void trace(const char *process_name, const char *msg)

void print(const char *msg)

// main.cpp

#include //#ifdef __cplusplus

#if defined(__cplusplus)

extern "c"

#endif

//extern int stdafxii;

int main(void)

// makefile

all: main

common.o: common.c

gcc -c common.c

main.o: main.c

g++ -c main.c

main: main.o common.o

g++ main.o common.o -o main

over

extern用法總結

在c語言中,修飾符extern用在變數或者函式的宣告前,用來說明 此變數 函式是在別處定義的,要在此處引用 1.extern修飾變數的宣告。如果檔案a.c需要引用b.c中變數int v,就可以在a.c中宣告extern int v,然後就可以引用變數v。這裡需要注意的是,被引用的變數v的鏈結屬性必須...

關於extern對變數的使用

extern 是宣告全域性的變數的意思。例如在乙個工程中有兩個cpp,乙個是test.cpp乙個是main.cpp 我們在test.cpp中定義了乙個int num 但是我們在main.cpp中想要呼叫。這時候我們就需要使用到extern 在main.cpp中進行宣告extern int num 這...

C語言 extern宣告的總結

c語言 extern宣告的總結1 基本解釋 extern可以置於變數或者函式前,以標示變數或者函式的定義在別的檔案中,提示編譯器遇到此變數和函式時在其他模組中尋找其定義。另外,extern也可用來進行鏈結指定。2 問題 extern 變數 在乙個原始檔裡定義了乙個陣列 char a 6 在另外乙個檔...