原因就是头文件里包含了函数定义,而该头文件被多次包含。
错误示例:
main.cpp如下:
#include "hello.h"
int main(int argc, char *argv[])
{
Hello * h = new Hello;
return 1;
}
hello.h如下:
#ifndef HELLO_H
#define HELLO_H
void abc()
{
int c = 0;
}
class Hello
{
public:
Hello();
public:
Print()
{
int a = 0;
}
};
#endif // HELLO_H
hello.cpp如下:
#include "hello.h"
Hello::Hello()
{
}
错误信息:
E:\StudyProject\test\redefinedError\hello.h:5: error: multiple definition of `abc()'
E:\StudyProject\test\redefinedError\hello.h:5: first defined here
注意,类里的成员函数是可以定义在头文件的。
hello.cpp和main.cpp这两个文件都包含了hello.h,多次包含就造成了重定义的错误。