遇到重定义的编译错误,把 #include "SerialPort.h" 放在.cpp文件里就正常编译,放进.h文件就编译报重定义;

In file included from /opt/RV1126/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/arm-linux-gnueabihf/libc/usr/include/asm/termbits.h:1,
                 from /home/ac/work/SerialPort.h:14,
                 from /home/ac/work/BluetoothTransparentModule_Impl.h:23,
/opt/RV1126/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/arm-linux-gnueabihf/libc/usr/include/asm-generic/termbits.h:12:8: 错误: ‘struct termios’重定义
 struct termios {
        ^~~~~~~


In file included from /opt/RV1126/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/arm-linux-gnueabihf/libc/usr/include/termios.h:39,
                 from /home/ac/work/ThirdPartyLib/boost/include/boost/asio/serial_port_base.hpp:25,
                 from /home/ac/work/ThirdPartyLib/boost/include/boost/asio/basic_serial_port.hpp:34,
                 from /home/ac/work/ThirdPartyLib/boost/include/boost/asio.hpp:34,
/opt/RV1126/gcc-arm-8.3-2019.03-x86_64-arm-linux-gnueabihf/arm-linux-gnueabihf/libc/usr/include/bits/termios.h:28:8: 附注: previous definition of ‘struct termios’
 struct termios
        ^~~~~~~

报错时的.h文件写法:

#include "BluetoothTransparentModule.h"
#include "SerialPort.h"

namespace bluetoothtransparent {

class BluetoothTransparentModule_Impl : public BluetoothTransparentModule {
 public:
    BluetoothTransparentModule_Impl();
    virtual ~BluetoothTransparentModule_Impl();

    bool Init(void) override;
    bool Uninit(void) override;

 private:

    kapok_hardware::SerialPort sdev;

};
}    /* namespace bluetoothtransparent */

解决办法把.h修改为:

#include "BluetoothTransparentModule.h"

namespace hardware {
    class SerialPort;
}

namespace bluetoothtransparent {

class BluetoothTransparentModule_Impl : public BluetoothTransparentModule {
 public:
    BluetoothTransparentModule_Impl();
    virtual ~BluetoothTransparentModule_Impl();

    bool Init(void) override;
    bool Uninit(void) override;

 private:
    hardware::SerialPort *sdev;
};
}    /* namespace bluetoothtransparent */

把#include "SerialPort.h"从.h文件里删除,在.cpp文件里包含#include "SerialPort.h"。

重定义的问题,可用 #ifndef FileName_H_ ,或者 #pragma once来处理,也可以把重定义的文件的struct、变量名、常量,提出到一个公共的.h文件中,这三种方法都试过了,不行。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐