我不太明白在C++中使用extern
和const
關鍵字的背後的概念。爲什麼我不能使用外部常量定義數組?
我已閱讀了有關該主題的一些相關問題(請參閱下面的),但到目前爲止,我一直無法掌握如何將它們一起使用。
相關問題:
- How do I share a variable between source files in C? With
extern
, but how? - What is the Difference Between a Definition and a Declaration?
- What is a Translation (Compilation) Unit?
- What Exactly is the One Definition Rule in C++?
好的,採取例如以下的程序代碼:
dConst.hpp
extern const int NUM_GENERATORS; // Number of generators in power plant
extern const int generatorID[NUM_GENERATORS]; // Generator ID numbers
extern const bool generatorStatus[NUM_GENERATORS]; // Generator Status
vConst.cpp
const int NUM_GENERATORS = 4; // Generators in Power Plant
const int generatorID[NUM_GENERATORS] = // Generator ID numbers
{
23, 57, 49, 106
};
const bool generatorStatus[NUM_GENERATORS] = // Production status (online?)
{
true, false, false, true
};
的main.cpp
#include <iostream>
#include "dConst.hpp"
using std::cout;
using std::cin;
using std::endl;
// ----====< M A I N >====----
int main()
{
for (int iGenerator = 0; iGenerator < NUM_GENERATORS; iGenerator++)
{
cout << "Generator ";
cout << generatorID[iGenerator];
if (generatorStatus[iGenerator])
cout << "is running." << endl;
else
cout << "is offline!" << endl;
}
cout << "Press ENTER to EXIT:";
cin.get(); // Stop
return 0;
}
我無法使用NUM_GENERATORS
來聲明我的數組充滿發生器ID和狀態。我已經在頂部包含了外部定義:#include "dConst.hpp
。從我讀過的一些StackOverflow問題(可能不夠緊密),編譯器和鏈接器應該能夠找到在vConst.cpp中定義的值,並繼續他們的快樂方式。
那麼他們爲什麼不這樣做呢?
所以我需要將這些常量的聲明包含在* vConst.cpp *到* main.cpp *中。如果我必須在另一個源文件中使用這些相同的常量,比如* powerPlant.cpp *,那麼我不會最終重新聲明那些常量[One Definition Rule](http://stackoverflow.com/questions/) 4192170 /什麼,恰好是一定義規則,在-C)? –