我如何避免“ ...”的“多重定义”。在这种情况下错误
Boardcomputer.h:
#ifndef BOARDCOMPUTER_H
#define BOARDCOMPUTER_H
#include <Arduino.h>
#include <TFT_eSPI.h>
TFT_eSPI disp = TFT_eSPI();
...
#endif
Boardcomputer.cpp:
#include <Boardcomputer.h>
^^use disp functions^^
...
错误:
.pio\build\EmmaChip\lib782\libBoardcomputer.a(Boardcomputer.cpp.o):(.bss.disp+0x0): multiple definition of `disp'
.pio\build\EmmaChip\src\main.cpp.o:(.bss.disp+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\EmmaChip\firmware.elf] Error 1
这是我尝试过的:
- 创建一个额外的头文件并在顶部添加
#pragma Once
- 创建一个额外的 Lib 并添加典型的
#ifndef ; #定义; #endif
行
你有解决这个问题的想法吗? 我没有多次定义“disp”。仅在一个标题中。
Boardcomputer.h:
#ifndef BOARDCOMPUTER_H
#define BOARDCOMPUTER_H
#include <Arduino.h>
#include <TFT_eSPI.h>
TFT_eSPI disp = TFT_eSPI();
...
#endif
Boardcomputer.cpp:
#include <Boardcomputer.h>
^^use disp functions^^
...
Error:
.pio\build\EmmaChip\lib782\libBoardcomputer.a(Boardcomputer.cpp.o):(.bss.disp+0x0): multiple definition of `disp'
.pio\build\EmmaChip\src\main.cpp.o:(.bss.disp+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
*** [.pio\build\EmmaChip\firmware.elf] Error 1
Here is what I tried:
- make an extra Header-File and add
#pragma once
at the top - make an extra Lib and add the typical
#ifndef; #define; #endif
lines
Do you have some ideas to fix this problem?
I don't define 'disp' multiple times. Just in one Header.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在这里:
您在头文件中定义了
disp
。在头文件中定义变量是完全错误的,它无法工作(除非您将 .h 文件包含在单个 .c 文件中,但无论如何 .h 文件都是毫无意义的),并且它会导致这些“多重定义”问题链接时间。这种情况发生在这里:
Boardcomputer.h
包含在foo.c
中,因此foo.o
将包含一个变量disp
>。代码编译良好。Boardcomputer.h
包含在bar.c
中,因此bar.o
将包含变量disp
。代码编译良好。foo.o
和bar.o
以生成可执行文件,链接器会看到两个变量disp
,其中一个位于bar.o
和foo.o
中的一个,因此出现多重定义错误您想要这个:
Boardcomputer.h
Boardcomputer.c
The problem is here:
You define
disp
in a header file. Defining variables in header files is plain wrong, it cannot work (except if you include the .h file in a single .c file, but then the .h file is pretty pointless anyway) and it leads to these "multiple definition" issues at link time.This happens here:
Boardcomputer.h
infoo.c
, thereforefoo.o
will contain a variabledisp
. The code compile fine.Boardcomputer.h
inbar.c
, thereforebar.o
will contain a variabledisp
. The code compile fine.foo.o
andbar.o
in order to produce an executable, and the linker sees two variablesdisp
, one inbar.o
and one infoo.o
, hence the multiple definition errorYou want this:
Boardcomputer.h
Boardcomputer.c