【问题标题】:Compiling arrays stored in external text files (C++ compiled using command line g++)编译存储在外部文本文件中的数组(使用命令行 g++ 编译的 C++)
【发布时间】:2013-06-17 21:57:34
【问题描述】:

我是一个新手 C++ 程序员,所以如果这是一个幼稚的问题,请原谅我。我有包含大型数组的文件,其中包含我以前在 javascript 应用程序中使用过的数万个字符串。有没有办法将这些包含到 C++ 源代码中,以便数组与代码一起编译?

目前,文件被格式化为返回 (javascript) 文字数组的函数,如下所示:

// javascript array stored in .js text file
function returnMyArray()
{
return ["string1", "string2", "string3", ... "stringBigNumber"];
} // eof returnMyArray()

我用常用的 javascript 脚本和 src 标签“包含”外部文件,并为数组分配如下内容:

myArray = returnMyArray();

我想在 c++ 中实现等价,即将存储在文件中的数组分配给我的 c++ 源代码中的数组,以便在编译时可以执行数据。

我想理论上我可以从文件中复制和粘贴(适当格式的)数组到我的 c++ 源代码中,但是它们太大了,不实用。

我可以轻松地将文件重写为任何最容易让 c++ 访问数据的格式 - 使用 c++ 数组语法或每行一个字符串以读取到数组中。

类似地,在终端中使用 g++ 编译时,是否有一种简单的方法可以包含包含自定义函数库的文件? (我的网络搜索显示了各种 IDE 应用程序的多种方法,但我在 vim 中编写源代码并在命令行上使用 g++ 编译)。

如果这是微不足道的,我很抱歉,我错过了,但我很难过!

谢谢。

【问题讨论】:

  • 您可以调整格式,以便将它们编写为有效的 C++ 数组定义,然后#include 它们。但是,如果不编写某种解析器或可怕的预处理器黑客,就无法让它工作,将它们作为原生 javascript。
  • @Wug 谢谢。我感觉有点笨,但是你特别提到#include 解决了这个问题......我已经了解了标题等,但它没有点击我也可以#include 来自文件的本机代码。我刚刚进行了实验,可以使用#include 加载存储在.cpp 文件中的数组,甚至可以作为函数中的本地数组。正是我需要的!简单!
  • 我会添加一个确切的答案,以防你好奇。
  • @Wug 我正要问 - 我如何在没有答案的情况下投票给你!是的,请给个答案。
  • @greatwolf - 是的,javascript 语法必须删除,但我只是通过 .js 文件编辑了所有内容,包括开头 [和关闭之后的所有内容] 以留下逗号分隔的列表带引号的字符串,将其重命名为 .cpp 并使用:'code' string myArray [] = { #include "arrayList.cpp" } ;

标签: c++ arrays include g++ external


【解决方案1】:

这是我的结构:

文件:data.array

/* C++ style comments are ok in this file and will be ignored
 * both single and multiline comments will work */

// the data in the array is a comma seperated list, lines can be any length
    1, 2, 3, 4,
    5, 6, 7, 8,
    9, 10, 11, 12,
    // more comma seperated data
    9996, 9997, 9998, 9999

文件:class.h

extern int myArray[]; // you should fill in the size if you can
// more stuff here

文件:class.cpp

// if you have an editor that highlights syntax and errors, it may not like this
// however, #include is handled before compiling and performs a blind substitution
// so this is perfectly legal and should compile.
// Visual C++ 2010 highlights this as an error, but the project builds fine.

int myArray[]
{
    #include "data.array"
};

// other definitions of stuff in class.h

【讨论】:

  • 谢谢。 class.h 文件有什么作用?在我的实验中,我将数组写在一个文件中,并简单地使用#include 在源代码中需要的地方引用它——它工作得很好,但是如果没有 class.h 会导致问题吗?而且,class.h 是否包含在所有函数之外的标题中?
  • 如果要在其他文件中使用该数组,就必须这样声明。
猜你喜欢
  • 1970-01-01
  • 2017-09-24
  • 2021-12-12
  • 1970-01-01
  • 2021-08-19
  • 2023-03-14
  • 1970-01-01
  • 2016-11-17
  • 1970-01-01
相关资源
最近更新 更多