C 中static內部鏈結和extern外部鏈結

2021-10-02 14:04:30 字數 1695 閱讀 1531

我們在進行多檔案編譯時,會遇到在不同檔案中存在同名變數的問題,但是相同變數存在兩種情況:

1、兩個檔案中的同名變數實際上是相同的變數

2、兩個檔案中的同名變數實際上是不同的變數

對於第一種情況,實際上相同的意思是兩個變數的位址也一樣,就是相同的變數,但是宣告在不同的檔案中而已。對於這種情況,我們c++引入了extern關鍵字

#include

using

namespace std;

int count =10;

void

printing()

;int

main()

file1.cpp中定義了乙個全域性變數count,並且在main函式中進行自增運算。

#include

using

namespace std;

extern

int count;

void

printing()

file2.cpp中宣告了乙個外部鏈結extern同名變數,是的可以在file2.cpp中使用該變數,實際上這兩個變數是同乙個變數。

編譯兩個檔案,輸出count自增之後的數值!

ps d:\程式\隨筆程式\2023年1月》 g++ file1.cpp file2.cpp -o main

ps d:\程式\隨筆程式\2023年1月》 ./main

11

在文首的第二種情況中,兩個檔案中的變數只是同名,但是實際上是不同的變數,也儲存在不同的位址。

#include

using

namespace std;

int count =4;

void

printing()

;int

main()

file1.cpp中宣告了乙個全域性的int變數,自增後輸出

#include

using

namespace std;

static

int count =9;

void

printing()

file2.cpp中也定義了乙個同名變數,並且是使用static關鍵字進行內部鏈結,因此,兩個變數實則不同。

file1.cppmain函式通過呼叫file2.cpp中實現的函式,來輸出file2.cpp中的count變數。

ps d:\程式\隨筆程式\2023年1月》 g++ file1.cpp file2.cpp -o main

ps d:\程式\隨筆程式\2023年1月》 ./main

count in file1:5

count in file2:9

C 中的內部鏈結和外部鏈結

c 中的內部連線與外部連線 apr 22nd,2007 by king 一.在學習內部連線與外部連線之前,必須先弄清楚幾個概念 1.宣告 乙個宣告將乙個名稱引入乙個作用域。在c 中,在乙個作用域中重複乙個宣告是合法的。以下都是宣告 int foo int,int 函式前置宣告 typedef int...

c 內部鏈結 外部鏈結

c 內部鏈結與外部鏈結 2009年03月12日 星期四 11 07 在說內部連線與外部連線前,先說明一些概念。1.宣告 乙個宣告將乙個名稱引入乙個作用域 在c 中,在乙個作用域中重複乙個宣告是合法的 以下都是宣告 int foo int,int 函式前置宣告 typedef int int type...

C 中的內部鏈結屬性。。。

template class myclass char const s hello myclassx error s is pointer to object with internal linkage 這裡 hello 是個內部鏈結 internal linkage 物件 但是 template ...