Silly Computer Engineer.
Lin~Jing~Sen
Something as small as the flutter of the butterfly's wing
can ultimately cause a typoon half way around the world

Group Blog
 
All Blogs
 
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 น. 2 comments
Counter : 856 Pageviews.

 
น่าเบื่อซี


โดย: vbvbvbbvbvb IP: 61.19.21.20 วันที่: 2 กุมภาพันธ์ 2549 เวลา:11:47:53 น.  

 
ใช้
#pragma once ก็ได้มัง้ค่ะ ถ้าจำไม่ผิด


โดย: เด็กเล็ก วันที่: 5 กุมภาพันธ์ 2549 เวลา:3:16:22 น.  

ชื่อ :
Comment :
  *ใช้ code html ตกแต่งข้อความได้เฉพาะสมาชิก
 

nmapxp
Location :
กรุงเทพ Thailand

[Profile ทั้งหมด]

ฝากข้อความหลังไมค์
Rss Feed

ผู้ติดตามบล็อก : 1 คน [?]





Friends' blogs
[Add nmapxp's blog to your web]
Links
 

 Pantip.com | PantipMarket.com | Pantown.com | © 2004 BlogGang.com allrights reserved.