首页 > 解决方案 > 当头文件(a.hpp)包含在头文件(b.hpp)对应的源文件(b.cpp)和main.cpp中时,C ++修复多重定义错误

问题描述

我在 Ubuntu 16.04LTS 中有以下四个文件a.hppb.hppb.cppmain.cpp,它们模仿了我的原始文件。

一个.hpp

#ifndef A_H
#define A_H

#include <iostream>

namespace Utility{
    typedef struct _structure{
        int v;
        int w;
    }aStructure;

    void foo(){
        std::cout << "foo" << std::endl;
    }

    void goo(){
        foo();
    }
}

#endif

b.hpp

#ifndef B_H
#define B_H

#include <iostream>

#include "a.hpp"

class bCls{
    private:
        int x;
    public:
        void moo(Utility::aStructure s);
};

#endif

b.cpp

#include <iostream>

#include "a.hpp"
#include "b.hpp"

void bCls::moo(Utility::aStructure s){
    std::cout << "moo" << std::endl;
}

主文件

#include <iostream>

#include "a.hpp"
#include "b.hpp"

int main(){

    Utility::aStructure s;
    bCls u;

    u.moo(s);

    return 0;
}

当我尝试使用g++ -std=c++11 b.cpp main.cpp进行编译时,会抛出以下错误消息:

/tmp/ccwvPrRr.o: In function `Utility::foo()':
main.cpp:(.text+0x0): multiple definition of `Utility::foo()'
/tmp/ccCVJOoH.o:b.cpp:(.text+0x0): first defined here
/tmp/ccwvPrRr.o: In function `Utility::goo()':
main.cpp:(.text+0x23): multiple definition of `Utility::goo()'
/tmp/ccCVJOoH.o:b.cpp:(.text+0x23): first defined here
collect2: error: ld returned 1 exit status

我的搜索导致包含标题时为什么会出现多个定义错误?. 但我的代码中的一个区别是b.hppb.cppmain.cpp都需要a.hpp

我很想知道我做错了什么以及在这种情况下编写代码的最佳方法以及相应的陷阱。

标签: c++headernamespaces

解决方案


推荐阅读