c++ - 定义 const 变量不能跨头文件工作

标签 c++ g++ raspberry-pi

我目前正在为 Raspberry Pi 开发一个小程序。它涉及一些 7 段显示器。为了能够为此显示器编写更多程序,我决定将直接与 GPIO 通信的代码提取到单独的 .cpp 和 .h 文件中。

由于位数是可变的,因此我为此使用了一个变量。数字本身存储在一个由 8 位整数组成的数组中。

这是我的设置:

7_segment.h:

extern const uint8_t numDigits;
extern uint8_t digits[];

7_segment.cpp:

#include "7_Segment.h"

uint8_t digits[numDigits] = {0x00}; // Line 7

以及包含“实际”程序的文件:
时钟.cpp:

#include "7_Segment.h"

const uint8_t numDigits = 4;

当我执行

g++ clock.cpp 7_segment.cpp -o clock -std=c++0x -lwiringPi

我得到这个输出:

7_segment.cpp:7:27: error: array bound is not an integer constant before ‘]’ token

我该怎么做才能解决这个问题?

最佳答案

numDigits=4 在 clock.cpp 中定义。 7_segment.cpp 不知道数组 digits[] 的大小。数组大小需要是编译时常量,因此您需要将实际数字放在 7_segment.cpp 中或作为编译时常量放在 7_segment.h 中。

关于c++ - 定义 const 变量不能跨头文件工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25792424/

相关文章:

linux - PiDora PAM 允许 root 登录,但有时会拒绝

raspberry-pi - 使用 scapy 进行 channel 跳跃嗅探数据包

c++ - 我可以从对象外部调用 VFunc 吗?

c++ - 为什么在使用 -O3 标志函数编译 C++ 代码后生成错误的输出?

cmake - 在 cmake 混合语言项目中使用 FORTRAN 链接器

c++ - 外部符号如何解析?

python - 如何在 Python 的 struct 中使用 C++ struct

c++ - 分配给类中函数指针的函数

c++ - 弄清楚我对指针和引用的概念

javascript - 为 Raspberry Pi 构建 Node.js 发生了什么