3 回答

TA貢獻1883條經驗 獲得超3個贊
全局變量應extern在兩個源文件都包含的頭文件中聲明,然后僅在這些源文件之一中定義:
普通
extern int global;
source1.cpp
#include "common.h"
int global;
int function();
int main()
{
global=42;
function();
return 0;
}
source2.cpp
#include "common.h"
int function()
{
if(global==42)
return 42;
return 0;
}

TA貢獻1860條經驗 獲得超9個贊
您添加一個“頭文件”,該文件描述模塊source1.cpp的接口:
source1.h
#ifndef SOURCE1_H_
#define SOURCE1_H_
extern int global;
#endif
source2.h
#ifndef SOURCE2_H_
#define SOURCE2_H_
int function();
#endif
并在每個使用此變量的文件中添加#include語句,并在(重要)變量中定義該變量。
source1.cpp
#include "source1.h"
#include "source2.h"
int global;
int main()
{
global=42;
function();
return 0;
}
source2.cpp
#include "source1.h"
#include "source2.h"
int function()
{
if(global==42)
return 42;
return 0;
}
盡管沒有必要,但我建議為該文件使用名稱source1.h,以表明它描述了模塊source1.cpp的公共接口。以相同的方式,source2.h描述了source2.cpp中公共可用的內容。
- 3 回答
- 0 關注
- 560 瀏覽
添加回答
舉報