एक चाल है जिसका उपयोग आप टेम्पलेट्स के साथ एच फाइल को केवल स्थिरांक प्रदान करने के लिए कर सकते हैं।
(ध्यान दें, यह एक बदसूरत उदाहरण है, लेकिन कम से कम छ ++ 4.6.1। में में शब्दशः काम करता है)
(values.hpp फ़ाइल)
#include <string>
template<int dummy>
class tValues
{
public:
static const char* myValue;
};
template <int dummy> const char* tValues<dummy>::myValue = "This is a value";
typedef tValues<0> Values;
std::string otherCompUnit(); // test from other compilation unit
(main.cpp)
#include <iostream>
#include "values.hpp"
int main()
{
std::cout << "from main: " << Values::myValue << std::endl;
std::cout << "from other: " << otherCompUnit() << std::endl;
}
(other.cpp)
#include "values.hpp"
std::string otherCompUnit() {
return std::string(Values::myValue);
}
संकलन (उदा। other.cpp & & ./main जी ++ -ओ मुख्य main.cpp) और दो संकलन इकाइयों एक ही निरंतर एक शीर्षक में घोषित संदर्भित देखें:
from main: This is a value
from other: This is a value
MSVC में, आप के बजाय का उपयोग करने में सक्षम हो सकता __declspec (selectany)
उदाहरण के लिए:
__declspec(selectany) const char* data = "My data";
आप "स्थिर स्थिरांक चार * स्थिरांक कुछ" का उपयोग करना चाहिए बजाय जब तक आप वास्तव में:
अपने संकलक पर निर्भर करता है, आप भी .cpp फ़ाइल में एक स्पष्ट परिभाषा लिखने के लिए आवश्यकता हो सकती है रनटाइम पर किसी और चीज पर इंगित करने के लिए कुछ पुनः पुन: असाइन करने में सक्षम होना चाहते हैं। – bk1e