का कारण बनता है मैं पहले परिभाषित चर का उपयोग करने के लिए बाहरी का उपयोग करने की कोशिश कर रहा हूं।बाहरी चर कई परिभाषा त्रुटि
मैंने पहले निर्वासन इस्तेमाल नहीं किया है और अब मैं आदेश सिर्फ एक बार चर को परिभाषित करने और उन्हें एकाधिक फ़ाइलों
मैं इस सवाल के लिए कोड की कम से कम संस्करण में लिखा है भर में उपयोग करने के लिए इसका इस्तेमाल करने की जरूरत है। मैं चार फ़ाइलों
है
#ifndef LIB_H
#define LIB_H
#include <iostream>
namespace lib {
extern bool initialized;
bool initialized = false;
static void isInit(char* parent) {
std::cout << "Library for [" << parent << "] initialized? " << (::lib::initialized ? "yes" : "no") << "\n";
}
} // namespace lib
#endif
vehicle.h
#ifndef _VEHICLE_H
#define _VEHICLE_H
#include <string>
class Vehicle {
public:
Vehicle(const std::string& manufacturer,
const std::string& model,
int year);
std::string manufacturer;
std::string model;
int year;
};
#endif
बाद lib.h vehicle.cpp
#include "vehicle.h"
#include "lib.h"
Vehicle::Vehicle(const std::string& manufacturer,
const std::string& model,
int year) :
manufacturer(manufacturer),
model(model),
year(year) {
::lib::isInit("Vehicle");
}
मुख्य बुलाया vehicle.h फ़ाइल के कार्यान्वयन है .cpp
/tmp/cclVpsgT.o:(.bss+0x0): multiple definition of `lib::initialized'
/tmp/ccmJKImL.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
मैं के उत्पादन में जाँच की है:
g++ -Wno-write-strings main.cpp vehicle.cpp -E
कई परिभाषा हर बार lib.h होता
#include "vehicle.h"
#include "lib.h"
int main(int argc, char** argv) {
::lib::isInit("main");
::lib::initialized = true;
::lib::isInit("main");
Vehicle vehicle("Toyota", "Corolla", 2013);
return 0;
}
मैं जी ++
g++ -Wno-write-strings main.cpp vehicle.cpp -o bin/main.cpp.bin
उपयोग कर रहा हूँ मैं निम्नलिखित त्रुटियाँ प्राप्त शामिल है।
मेरे प्रश्न हैं:
- lib.h कई बार शामिल जब गार्ड को परिभाषित है क्यों है वहाँ
- मैं कैसे परिभाषित करेंगे 'निर्वासन' चर और एक फ़ाइल में यह प्रारंभ (क्योंकि यह में प्रयोग किया जाता है एक ही फाइल बाद में)
क्या एक ही फाइल में ऐसा करने का कोई तरीका नहीं है? – abumusamq
@ mkhan3189: क्या दूसरे प्रश्न का उत्तर आपकी टिप्पणी में क्यू का उत्तर देता है? –
हां यह करता है :) इसे उत्तर के रूप में चिह्नित करना क्योंकि यह मेरे प्रश्न का उत्तर देता है। मेरा मानना है कि एक ही फाइल में बाहरी होने के बाद से शुरू करने का कोई तरीका नहीं है। – abumusamq