C++ 在多个其他类中使用单个类 - 编译时出现多个定义错误

C++ Using a single class in multiple other classes - Multiple definition error when compiling

本文关键字:编译 定义 错误 其他 C++ 单个类      更新时间:2023-10-16

我下载了一个库,用于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 目录。