我是一名新手 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/