[c語言]multiple definition of 'function()'可能錯誤原因

原因就是頭文件裏包含了函數定義,而該頭文件被多次包含。

錯誤示例:

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,多次包含就造成了重定義的錯誤。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章