C++ Error:: redefinition of
ระวังการเขียน C++ แล้วมีการ include วนลูป เช่น มี source code อยู่ 2 ไฟล์ ชื่อ tor.cc และ tem.cc และมี H file อยู่ 2 ไฟล์คือ tor.h และ tem.h
========= tor.h ========= #include "tem.h" #define TOR 3
========= tor.cc =========
#include "tor.h"
int main() {}
========= tem.h ========= #include "tor.h" #define TEM 99
struct a { } ========= tem.cc ========= #include "tem.h" int main() {}
จะเห็นได้ว่า ในไฟล์ tor.h และ tem.h มีการ #include ซึ่งกันและกัน ดังนั้นเวลา complile จะมีการเตือนว่ามีการ include เป็นวง และ error เนื่องจากมีการประกาศ "struct a" สองครั้งเพราะการวนลูป
In file included from tor.h:1, from tor.h:1, from tor.h:1, from tor.h:1, from tor.h:1, from tem.cc:2:
tem.h:4: error: previous definition of struct a tem.h:4: error: redefinition of struct a
วิธีแก้ ก็ใช้ derivative #ifndef ครอบ ที่ H file เพื่อป้องกันการประกาศซ้ำ
========= tor.h ========= #ifndef _tor_h_ #define _tor_h_ #include "tem.h" #define TOR 3
#endif
========= tem.h ========= #ifndef _tem_h_ #define _tem_h_ #include "tor.h" #define TEM 99
struct a { }
#endif
compiler ก็จะตรวจสอบว่า derivative _tor_h_ เคยถูกประกาศรือไม่ ถ้าไม่เคย ก็จะประกาศและทำตามบรรทัดต่อๆมา
ถ้า compiler พบว่ามี derivative _tor_h_ อยู่แล้ว ก็จะไม่ทำต่อ เป็นการinclude มาครั้งเดียว
Create Date : 26 มกราคม 2549 | | |
Last Update : 8 เมษายน 2549 0:10:28 น. |
Counter : 852 Pageviews. |
| |
|
|
|