使用 header 的 Arduino 草图和添加了模板方法的代码文件。夹在 'undefined reference to' 和 'redefinition of' 之间

Arduino sketch with header and code file added with template methods. Caught between 'undefined reference to' and 'redefinition of'

我有一个 header 文件声明了一个方法,还有一个包含实现的代码文件。编译时,编译器出错 'undefined reference to...'。如果我将方法的实现复制到 header,它会告诉我该方法正在代码文件中重新定义。当然如果它能在cpp文件中找到调用副本的方法,那么它就可以使用它。由于找不到,所以将其添加到 header 应该不会导致重新定义。

所有 header 都受到保护。在下面的代码中,如果我取消注释 header 实现,该方法将被重新定义,如果我将其保留注释,则该方法未定义。如果我只使用 header 实现,一切都可以正常编译,但架构不好。 cpp 文件被正确复制到输出文件夹。示例代码:

test.ino

#include "math.h"

void setup() {
  int result = Math::Double((int)2);
}

void loop() {}

math.h

#ifndef MATH_H
#define MATH_H

namespace Math {
  template <typename U>
  U Double(U value);

//  template <typename U>
//  U Interpolate(U value) {
//    return value * 2;       ​
//  ​}

}

#endif

math.cpp

#include "math.h"

template <typename U>
U Math::Double(U value) {
  return value * 2;       ​
}

您的代码中存在一些 C++ 语法错误。

  1. 模板必须在头文件中声明和定义(很少有语法对此提供例外,但我不会在这里讨论)。
  2. 您的 'loop' 函数定义前缺少括号。
  3. 您正在使用名称“value”声明 Double 参数,但随后试图使用名称“result”来使用它

这是更正后的代码:

编辑 将此更改为单独的模板 declarations/definitions。原答案将在修改后的那一行星号下方。

math.h

#ifndef MATH_H
#define MATH_H

namespace Math {
  template <typename U>
  U Double(U value);
}

#include "math_ipp.h"
#endif

math_ipp.h

#ifndef MATHIPP_H
#define MATHIPP_H
#include "math.h"

namespace Math {
  template <typename U>
  U Double(U value) {
    return value * 2;
  }
}

#endif

test.ino

#include "math.h"

void setup() {
  int result = Math::Double((int)2);
}

void loop() {}

********** 下面是原始答案 math.h

#ifndef MATH_H
#define MATH_H

namespace Math {
  template <typename U>
  U Double(U value) {
    return value * 2;
  }
}

#endif

test.ino

#include "math.h"

void setup() {
  int result = Math::Double((int)2);
}

void loop() {}