【问题标题】:redefine printf(), sprintf(), etc. arm-none-eabi toolchain重新定义 printf()、sprintf() 等 arm-none-eabi 工具链
【发布时间】:2019-12-17 01:43:09
【问题描述】:

我正在使用 gcc-arm-none-eabi 工具链(当前为 7.2.1)设置和环境。这是针对 ARM cortex M4 嵌入式设备的。

我想为整个项目重新定义 printf,但我遇到了麻烦。我想使用this 实现。我已经将它安装到项目中,我可以通过调用来使用它,例如:printf_("Test: %i",5);,一切都按预期工作。

现在我想将它设置为默认的 printf 函数。如果我取消注释:#define printf printf_,我会收到以下错误:

/home/timv/.platformio/packages/toolchain-gccarmnoneeabi@1.70201.0/arm-none-eabi/include/c++/7.2.1/cstdio:127:11: error: '::printf' has not been declared
   using ::printf;

稍后:

src/LoggerTask.cpp:62:5: error: 'printf' was not declared in this scope

在那个文件中我找到了这一行:

#undef printf

当我注释掉该行时,项目构建,并且 printf 工作。这很好,但我想在不修补工具链的情况下拥有我的项目功能。

我该怎么做呢?还有哪些有用的信息?

【问题讨论】:

  • 您需要 C 解决方案还是只需要 C++ 解决方案?
  • 您为什么要在您的LoggerTask.cpp 中添加#undef printff I uncomment: #define printf printf_ - 定义位于哪个文件中?
  • 重新定义标准 C 名称是一个坏主意(令人困惑,并且可能是未定义的行为)。你不能在你的源代码中使用myprintf吗?

标签: c++ c arm embedded platformio


【解决方案1】:

您可以使用下一个示例创建指向printf 的指针。您需要创建帮助文件(在本例中名为“printf_helper.h”和“printf_helper.cpp”)。并将“printf_helper.h”(比所有其他包含的标头更好)包含到您要使用printf 的文件中。

printf_helper.h:

#ifndef PRINTF_HELPER_H
#define PRINTF_HELPER_H

namespace helper {
  typedef int (*printf_t) (const char * format, ...);
  extern const printf_t printf_ptr;
}

#endif /* PRINTF_HELPER_H */

printf_helper.cpp:

#include "printf_helper.h"
#include <cstdio>

namespace helper {
  const printf_t printf_ptr = std::printf;
}

main.cpp 中的使用示例:

// all other included headers
#include "printf_helper.h"

int main() {
  helper::printf_ptr("Hello, %s!\n", "World");
  return 0;
}

【讨论】:

    【解决方案2】:

    在你的编译中添加一个新文件:

    #include <stdarg.h>
    int vprintf_(const char* format, va_list va);
    int printf(const char *str, ...) {
         va_list va;
         va_start(va, str);
         int ret = vprintf_(str, va);
         va_end(va);
         return ret;
    }
    

    在创建编译输出时编译并链接结果对象。就这样。由于链接器的工作方式,链接器应该选择您的符号,而不是 newlib 提供的符号。或者,您可以使用 --wrap=printf 链接器选项来简单地包装符号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-23
      • 2022-01-14
      • 1970-01-01
      • 2016-05-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多