写程序的时候出现LN2005错误,调试发现是头文件包含的问题,我把问题简化了一下,如下
//file c.h
void fun()
{
...
}
//file a.cpp
#include "stdafx.h"
#include "c.h" void fun1()
{
fun();
}
//file b.cpp
#include "stdafx.h"
#include "c.h" void fun2()
{
fun();
} 这种情况下编译会报错
error LNK2005: "void __cdecl fun(void)" (?fun@@YAXXZ) 已经在 a.obj 中定义
1>C:\Documents and Settings\lhp\桌面\newproject\test\t7\Debug\t7.exe : fatal error LNK1169: 找到一个或多个多重定义的符号
如果我把fun1()和fun2()放到a.h和b.h中则正常晕了,这什么问题啊,请大家指教
//file c.h
void fun()
{
...
}
//file a.cpp
#include "stdafx.h"
#include "c.h" void fun1()
{
fun();
}
//file b.cpp
#include "stdafx.h"
#include "c.h" void fun2()
{
fun();
} 这种情况下编译会报错
error LNK2005: "void __cdecl fun(void)" (?fun@@YAXXZ) 已经在 a.obj 中定义
1>C:\Documents and Settings\lhp\桌面\newproject\test\t7\Debug\t7.exe : fatal error LNK1169: 找到一个或多个多重定义的符号
如果我把fun1()和fun2()放到a.h和b.h中则正常晕了,这什么问题啊,请大家指教
#ifndef A_H
#define A_H
在结尾加
#endif
在a.h中
extern void fun();
#define A_H
在结尾加
#endif
这个宏我知道,我在a.h和b.h中都加过,没有效果,后来我干脆把a.h和b.h都给删了,这两个文件都空的,还是不行。
extern 这个方法行得通
//file a.cpp
#include "stdafx.h"
#include "c.h" void fun1()
{
fun();
}
//file b.cpp
#include "stdafx.h"
extern void fun(); void fun2()
{
fun();
}
我知道这个错误是重复定义,但是到底是在哪里出现的重定义呢?哪位高人详细解释一下,楼上的谢谢了。
在a.h中
extern void fun();
#ifndef A_H
#define A_H
在结尾加
#endif
否则很容易重定义,除非你愿意写很多#ifdefine #endif来保护头文件头文件中只能有声明,或者const的全局变量定义,或者extern的全局变量声明
你的头文件里放了这个函数定义
void fun()
{
...
}
如果多个文件引用了这个头文件,就会重复定义了