C++ 在多个其他类中使用单个类 - 编译时出现多个定义错误
C++ Using a single class in multiple other classes - Multiple definition error when compiling
我下载了一个库,用于arduino,以便通过I2C与MCP23017芯片进行通信。我的目标是在各种文件中使用这个类来具有不同的功能,本质上是一个与这个芯片有关的东西库。
在构建代码以运行 7 段多路复用显示器后,一切都编译良好,并且能够加载到 arduino 上。在编写另一个类以仅将第二个芯片用于输入后,由于基类的多个定义,我开始出现编译错误。 我习惯于用 VB 编码,而不是C++,所以必须定义这样的类非常混乱,我不确定该怎么做才能解决它。
这是错误:(这只是错误的一个片段,因为我认为本节的要点已经足够好了。Adafruit_MCP23017.cpp文件中的每个例程都有此错误。
Adafruit_MCP23017.cpp.o (symbol from plugin)*: In function Adafruit_MCP23017::bitForPin(unsigned char)
(.text+0x0)*: multiple definition of Adafruit_MCP23017::readGPIO(unsigned char)
Adafruit_MCP23017.cpp.o (symbol from plugin)*: (.text+0x0): first defined here
主文件头:
#include <Arduino.h>
#include <Wire.h>
#include <unistd.h>
#include "SevenSegmentDisplay_MCP23017.h"
#include "I2C_Input_MCP23017.h"
SevenSegmentDisplay SSD;
I2C_Input_MCP23017 INP;
SevenSegmentDisplay.h Header:
#pragma once
#ifndef _Adafruit_MCP23017_H_
#include <Adafruit_MCP23017.h>
#endif
#include <Arduino.h> // Need for serial output and 'delay' function
七段显示.cpp标题:
#include "SevenSegmentDisplay_MCP23017.h"
I2C_Input_MCP23017.h 标头:
#pragma once
#include <Adafruit_MCP23017.h>
#include <Arduino.h> // Need for serial output and 'delay' function
I2C_Input_MCP23017.cpp标头:
#include "I2C_Input_MCP23017.h"
解决方案编辑:阅读某人发布的答案后,我发现了问题所在。我不认为基类是鼻烟(缺乏对例程的评论,使其很难使用,因为您没有描述每个例程接受的变量或它的作用。执行此操作时,我将其包含在解决方案中。问题是它从库文件夹和解决方案本身中包含它(即使解决方案仅引用库本身的文件,也不会创建新文件(。我删除了对相关类的引用(如下图所示突出显示(,程序编译完美。(通过重新添加它们进行测试,导致相同的故障(。
TL;DR:如果您的库中已经有该文件,请不要将其包含在解决方案中,因为它似乎想要抓取它两次。一次在 #included 时,一次在解决方案资源管理器中。
问题是这样的:
我怀疑您在Arduino/libraries目录中的两个位置都有Adafruit_MCP23017库(.c和.h文件(。
可能(可能!(在/libraries/Adafruit_MCP23017/和/libraries/SevenSegmentDisplay_MCP23017/utility/中
Adafruit 通过在下载存档中包含任何必需的子库来使其库成为初学者证明。但是一旦您尝试直接使用子库,它就会混淆事情。
如果是这种情况,则需要修改 SevenSegmentDisplay_MCP23017.h 文件以从
#include <utility/Adafruit_MCP23017.h>
自
#include <Adafruit_MCP23017.h>
并从/libraries/SevenSegmentDisplay_MCP23017/utility/中删除 Adafruit_MCP23017.h 和 Adafruit_MCP23017.c 目录。
- 编译C++时未定义的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 编译时的 CImg 库返回对"__imp_SetDIBitsToDevice"的未定义引用
- 未定义的引用 .. 使用 OpenCV 编译 C++ 代码时,从命令行
- 标准是否严格定义了该程序应该如何编译?
- 如何摆脱为条件编译定义预处理器宏的需要?
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 在编译它时显示未定义的引用
- 使用宏编译时使用用户定义的数学函数,或者仅使用 c++ 中标准数学库中的函数
- 编译问题:在函数"_start"中:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 良好做法:如何定义用于编译的外部库的路径
- 编译 libfluid 样本控制器时对"event_base_del_virtual"的未定义引用
- 如何在编译时定义C++预处理器指令的值?
- libssh 问题编译问题未定义的错误
- 编译 GPU 的张量流示例自定义操作
- 为什么我的C++代码无法编译,出现未定义的引用错误
- 为什么更改包含 psapi.h 的顺序会产生编译错误?(标识符 BOOL 未定义)
- 使用 C++17 编译特征需要_SILENCE_CXX17_NEGATORS_DEPRECATION_WARNING定义
- CMake:静态库和共享库的不同编译定义