【问题标题】:atmel studio ifndef compilation erroratmel studio ifndef 编译错误
【发布时间】:2015-06-25 08:37:24
【问题描述】:

嗨,imy 项目可以识别不存在 2 次的变量的双重定义。我想通过更改我的代码并重新编译它会卡住一些方法。

LedMatrix7219.cpp.o:(.data.Alphaletter+0x0): `Alphaletter'的多重定义 LedController.cpp.o:(.data.Alphaletter+0x0): first 在这里定义

LedMatrix7219.cpp.o:在函数“循环”中 LedController.cpp.o:(.bss.arr+0x0): 首先定义在这里

LedMatrix7219.cpp.o:在函数“循环”中 LedController.cpp.o:(.data.Alphaletter2+0x0): 这里先定义

collect2.exe*:error: ld 返回 1 个退出状态

我有一个 LedController 类和一个标头 LettersDefinition.h

所有的标题都是这样开始的:

我包含一个结构和一个从 LetterDefinition.h 到 LedController 的枚举,所以在标题中我需要包含 LetterDefinition.h 以进行一定的打击。

#ifndef __LEDCONTROLLER_H__
#define __LEDCONTROLLER_H__

#include <Arduino.h>
#include "LettersDefinition.h"

LetterStruct finalText;
String theText="Test";

void test();
//it does some extra staff
#endif //__LEDCONTROLLER_H__

以及字母定义的标题。

#ifndef LETTERSDEFINITION_H_
#define LETTERSDEFINITION_H_

#include "arduino.h"
#include <avr/pgmspace.h>

struct LetterStruct{

    lettersEnum name;
    uint8_t size;
    uint8_t columnSize[5];
    uint8_t data[18];
}Alphaletter;
#endif /* LETTERSDEFINITION_H_ */

从我的主 .ide 文件中,我调用了 Ledcontroller 的测试函数,我得到了你在上面看到的错误。测试函数只是检查 LetterStruct.name 变量而已。

我的 .ide 类似于:

#include <SPI.h>
#include <Adafruit_GFX.h>
#include <Max72xxPanel.h>
#include "LedController.h"   

LedController controller;

void setup()
{
    //irrelevant inits
}

void loop()
{
    controller.test();
    delay(2000);
}

如果我从 LedController.h 中删除 #include "LettersDefinition.h",则此错误将其定位为未在 LedController.h 中定义 LetterStruct 的错误,这是正常的,因为我必须添加 LettersDefinition.h为了被定义。

【问题讨论】:

  • 你确定你不是想把它定义为一个类型吗?
  • 如你所见,我只是声明了一个特定类型的字母结构,这就是我所做的一切。在 letterDefinition.h 中定义了敲击
  • 是的,你在两个不同的编译单元中声明它。
  • 标头不是编译单元。

标签: arduino code-cleanup atmel atmelstudio


【解决方案1】:

您的问题源于您在头文件中“定义”变量。这一般会导致多重定义问题,不是标准设计。

您需要遵循的模型是在源文件中定义一次:

//some.cpp
// this is define
int variableX = 5;

并在头文件中声明:

//some.h
// this is declare
extern int variableX;

包含头文件的所有其他源文件只处理“extern”行,它大致表示“最终程序中将存在一个 int variableX”。编译器运行每个 .cpp .c 文件并创建一个模块。对于定义变量的 some.cpp,它将创建变量 X。所有其他 .cpp 文件将仅具有作为占位符的外部引用。当链接器将所有模块组合在一起时,它将解析这些占位符。

在你的具体情况下,这意味着改变:

// .h file should only be externs:
extern LetterStruct finalText;
extern String theText;

// .cpp file contains definitions
LetterStruct finalText;
String theText="Test";

【讨论】:

  • 因为我想在类中使用 finalText 和 thetext 变量,所以我想它们没有问题。因为这样每个类的每个变量都应该是外部的,以便在 cpp 中定义并且没有问题
  • 类成员变量不要使用extern。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多