【问题标题】:Calling function defined in another header file in a class in C++ [duplicate]调用C++类中另一个头文件中定义的函数[重复]
【发布时间】:2015-01-22 13:59:08
【问题描述】:

我正在尝试在一个类中使用 shiftreg.h 和 shiftreg.cpp(我之前在我的主文件中成功使用过)并调用他的一个函数。遗憾的是没有编译并给出错误:'shiftWrite' 未在此范围内声明。我想我在每个头文件中都包含了每个头文件,他们应该找到彼此。出了什么问题?

这是 shiftreg.h:

#ifndef shiftreg_h
#define shiftreg_h

void shiftWrite(uint8_t data);

#endif

还有这个 shiftreg.cpp:

#include "ShiftReg.h"

void shiftWrite(uint8_t data) {
    do something;}

函数shiftWrite,我想用在下面的SegmentDisplay类的一个函数中,用SegmentDisplay.h

#ifndef SegmentDisplay_h
#define SegmentDisplay_h

#include <ShiftReg/shiftReg.h>

class SegmentDisplay{
public:
    void pickNumber(int x);
};

#endif

还有 SegmentDispplay.cpp:

#include "SegmentDisplay.h"

void SegmentDisplay::pickNumber(int x){
    shiftWrite(ONE);}

这一切都始于 Arduino 软件:

  #include "SegShift.h"

  SegmentDisplay dsp();

  int main(void){
      while(1){
          dsp.pickNumber(j);}}

【问题讨论】:

    标签: c++ include header-files


    【解决方案1】:

    您似乎包含两个不同的文件:

    在 ShiftReg.cpp 中执行:#include "ShiftReg.h"

    在 SegmentDisplay.h 你做#include &lt;ShiftReg/shiftReg.h&gt;

    (顺便说一下,我只想在您的 SegmentDisplay.cpp 中包含 shiftreg.h。)

    【讨论】:

    • ShiftReg.h 与 SegmentDisplay.h 位于不同的文件夹中。这就是我做 的原因。如果我不这样做,它甚至找不到库。
    • 我在 SegmentDisplay.cpp 中添加了#include ,但它给出了同样的错误
    【解决方案2】:

    我已将 ShiftReg.h 和 ShiftReg.cpp 文件添加到 SegmentDisplay 文件的文件夹中,它可以编译!很高兴在您的回答的帮助下我也解决了这个问题。

    但是,我想知道为什么当它们位于不同的文件夹中时我不能使用这些文件。有什么想法吗?

    【讨论】:

    • 您的问题出在 ShiftReg.cpp 中,您没有包含相同的文件。那个也应该是#include &lt;ShiftReg/ShiftReg.h&gt;
    • 当我将#include 添加到 ShiftReg.cpp 时,它也不起作用。计算机上只有一个名为 ShiftReg.h 的文件,位于 ShiftReg 文件夹中。
    【解决方案3】:

    在 SegmentDisplay.h 中,您必须包含 shiftreg.cpp 而不是 shiftreg.h

    否则代码看不到该函数声明

    【讨论】:

    • 在 SegmentDisplay.h 中将 #include 更改为 #include 会产生相同的错误
    • 在这种情况下,或者在大多数情况下,没有理由 #include .cpp 文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    相关资源
    最近更新 更多