[問題] 條件式編譯出問題嗎?

看板C_and_CPP作者 (生活以下)時間16年前 (2009/04/02 18:05), 編輯推噓2(204)
留言6則, 4人參與, 最新討論串1/1
錯誤訊息 C:\Documents and Settings\Administrator\桌面\myC++>g++ -o test test.cpp func.cpp C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp/cc8qeaaa.o(.data+0x0):func.cpp: multiple definition of `NS1::gain' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp/ccO0caaa.o(.data+0x0):test.cpp: first defined here C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp/cc8qeaaa.o(.data+0x8):func.cpp: multiple definition of `NS2::gain' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp/ccO0caaa.o(.data+0x8):test.cpp: first defined here collect2: ld returned 1 exit status first.h #ifndef FIRST_H #define FIRST_H namespace NS1 { double gain=5.9; struct member { char *name; int score; }; double func(double); } #endif second.h #ifndef SECOND_H #define SECOND_H namespace NS2 { double gain=2.6; struct member { char *name; int id; }; double func(double); } #endif func.cpp #include "first.h" #include "second.h" double NS1::func(double x) { return x*NS1::gain; } double NS2::func(double y) { return y*NS2::gain; } test.cpp #include <iostream> using namespace std; #include "first.h" #include "second.h" #include "first.h" #include "second.h" #include "first.h" #include "second.h" int main() { cout << "NS1::gain=" << NS1::gain << endl; cout << "NS2::gain=" << NS2::gain << endl; NS1::member john; NS2::member david; john.name="John"; john.score=53; david.name="david"; david.id=8; cout << (NS1::func(5.2)) << endl; cout << (NS2::func(3.1)) << endl; cout << john.name << " " << john.score << endl; cout << david.name << " " << david.id << endl; system("pause"); } 兩個.h檔我都有加#ifndef 為什麼還會出現multiple definition? 高手幫我解答一下吧 感謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 114.42.216.102

04/03 02:08, , 1F
extern
04/03 02:08, 1F

04/03 02:18, , 2F
不好意思 可以說詳細一點嗎 謝謝^^
04/03 02:18, 2F

04/03 10:14, , 3F
在 h 只放 gain 的宣告, 把定義放回 cpp
04/03 10:14, 3F

04/03 14:38, , 4F
你是說在first.h裡面只寫double gain 不要寫=5.9嗎?
04/03 14:38, 4F

04/03 15:02, , 5F
extern double gain;
04/03 15:02, 5F

04/03 15:38, , 6F
要學習 definition 與 declaration 的意義。
04/03 15:38, 6F
文章代碼(AID): #19rFvOFi (C_and_CPP)