c++ - 编译存储在外部文本文件中的数组(使用命令行g++编译的C++)

标签 c++ arrays include g++ external

我是一名新手 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++ 进行编译)。

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

谢谢。

最佳答案

以下是我的结构:

文件: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

关于c++ - 编译存储在外部文本文件中的数组(使用命令行g++编译的C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17157548/

相关文章:

asp-classic - 经典的 asp include virtual with backslash 在 IIS7.5 上不起作用(与斜杠一起工作)

c++ - QUrl 解析失败

c++ - 为什么纯虚拟/抽象类需要构造函数,特别是对于 protected const 成员变量?

c++ - 找不到标识符 FindFirstFile

javascript - 洗牌 meteor 集合

c++ - #在 C 中包含 iostream?

c++ - Fortran 中的指针与 C/C++ 中的指针究竟有何不同?

php - 从数组中删除与正则表达式不匹配的元素

javascript - 如何监听所有数组项?

android - findViewById在<include> d View 内的LinearLayout上返回null