【问题标题】:Include string in file on compilation编译时在文件中包含字符串
【发布时间】:2015-06-01 10:21:18
【问题描述】:

我使用teensy 和 matlab 处理一个团队项目,为了避免版本差异(例如,一个人使用版本 A 加载 teensy,而现在使用 matlab 的人拥有 B 版代码),我'd like to send a version string on pair.

但是,我希望版本字符串位于 matlab 代码和 teensy 之间的共享文件中,并且每次将程序加载到 teensy 时,都将其作为常量包含在编译中。

有点像:

const string version = "<included file content>";

matlab 本身可以在运行时读取它。

我想使用一个文件,其内容是对一个变量的赋值,该变量的名称由 teensy 和 matlab 共享,但是如果存在这样的解决方案,我更喜欢更优雅的解决方案,尤其是不包括从运行时的外部文件。

【问题讨论】:

  • 澄清一下,"&lt;included file&gt;" 中您是在寻找文件名还是内容?
  • 内容,为代码版本的字符串,如“1.0.0rc1”
  • 可以考虑gcc中的-Dblahblah

标签: c++ c compilation arduino


【解决方案1】:

一种方法就是像这样进行简单的设置:

版本.inc:

"1.0.0rc1";

main.cpp:

const string version = 
#include "version.inc"

...

请注意,=#include 之间的换行符是为了让编译器满意。此外,如果您不想在 .inc 文件中包含分号,您可以这样做:

main.cpp:

const string version = 
#include "version.inc"
; // Put the semicolon on a newline, again to keep the compiler happy


编辑:而不是.inc 文件,你真的可以拥有任何你想要的文件扩展名。这一切都取决于口味


编辑:如果你真的想要,你可以省略 .inc 文件中的引号,但这会导致这样的混乱代码:

版本.inc:

STRINGIFY(
    1.0.0rc1
);

main.cpp:

#define STRINGIFY(X) #X

const string version = 
#include "version.inc"
...


编辑:

正如@Ôrel 指出的那样,您可以在 Makefile 中处理version.h 或类似内容的生成。假设您正在运行 *nix 系统,您可以尝试这样的设置:

生成文件:

...
# "1.0.0rc1"; > version.h
echo \"`cat version.inc`\"\; > version.h
...

版本.inc:

1.0.0rc1

main.cpp:

const string version = 
#include "version.h"

【讨论】:

  • @WojciechFrohmberg OP 要求输入作为编译常量:“... and every time the program is loaded to the teensy, have it included on compilation as a constant”。似乎您只阅读了问题的一部分。 OP 要求在运行时将文件包含在 matlab 端
  • 我考虑过这个,有没有不带引号的方法?
  • @Levi 那是......令人担忧,因为我认为我在生产代码中使用了类似的东西。非常感谢!
  • 您可以通过 Makefile 进行操作,从 version.inc 生成 version.h 或更好的选择以避免错误操作,您可以使用提交 ID 生成版本。
  • 看起来很不错,虽然我不知道如何在arduino IDE中使用makefile,我去看看!
猜你喜欢
  • 1970-01-01
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 2019-02-25
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多