看板Programming
标 题Re: [问题] multiple definition in gcc?
发信站政大狂狷年少 (Sun Jul 8 21:10:06 2007)
转信站ptt!ctu-reader!ctu-peer!news.nctu!netnews.csie.nctu!news.cs.nthu!WHSHS
※ 引述《[email protected] (好人可以装酷吗)》之铭言:
> 贴个很简单的例子来说明multiple definition的问题..
> 有三个档案b.c, b.h 和 main.c, 执行gcc b.c main.c之後,产生如下的错误讯息
> /tmp/ccWtXLur.o(.data+0x0): multiple definition of `m'
> /tmp/ccwfCTTj.o(.data+0x0): first defined here
> 我以为说, 用#ifndef __B_H__等行, 可以确保b.h只会被include一次,
> 但是似乎在main.c 以及b.c中的include "b.h", 皆执行了#include "b.h"此行,
太天真了,
#include 的意思就是把档案内容贴上去的意思,
也就是说在 main.c 跟 b.c 开头都会 b.h 内的每一行,
编译 main.c 和 b.c 时 __B_H__ 都是 undefined 的状态,
理所当然 #ifndef __B_H__ 都会成立,
里面的 int m = 4; 一定会被编译到。
header guard 的用意不是你想的这样,
它是在防止在同一个 .c 面重复 include 同一个 file 两次,
通常是你又写了 c.h 档,
里面又 #include "b.h",
所以当你同时 #include "b.h" 和 #include "c.h" 时,
会隐性的 #include "b.h" 两次 (除非你打开 c.h 才看得出来),
这时使用 header guard 就能让下面这两行
#include "b.h"
#include "c.h"
变成
#ifndef __B_H__
#define __B_H__ <------- 这里 #define
int m = 4;
#endif
#ifndef __B_H__ <------- 这里发现已经 #define,跳过 #endif 之前的每一行
#define __B_H__
int m = 4;
#endif
/*
* c.h 内的剩余内容
*/
/*
* .c file 的档案内容
*/
> 因而造成multiple definition的问题.
> 不知道问题是在哪呢? 该如何做呢?
> 谢谢
> ==================================
> b.h:
> #ifndef __B_H__
> #define __B_H__
> int m = 4;
> #endif
> ----------------------
> b.c:
> #include "b.h"
> ----------------------
> main.c:
> #include "b.h"
> int main() {
> return 0;
> }
--
Ling-hua Tseng (
[email protected])
Department of Computer Science, National Tsing-Hua University
Interesting: C++, Compiler, PL/PD, OS, VM, Large-scale software design
Researching: Software pipelining for VLIW architectures
Homepage:
https://it.muds.net/~uranus
--
╔═══╗ ┼────────────────────────╮
║狂狷 ║ │
* Origin:[ 狂 狷 年 少 ] whshs.cs.nccu.edu.tw ╰─╮
║ 年少║ ┼╮
< IP:140.119.164.252 > ╰─╮
╚╦═╦╝ ╰
* From:61-230-219-135.dynamic.hinet.net
─╨─╨─ KGBBS ─ ◎ 遨翔"BBS"的狂狷不驯;属於年少的轻狂色彩 ◎