I am a novice c++ programmer so please forgive me if this is a naive question. I have files containing large arrays holding tens-of-thousands of strings that I have used previously in javascript applications. Is there some way to include these into C++ source code so that the arrays are compiled along with the code?
At present, the files are formatted as functions that return (javascript) literal arrays, like this:
// javascript array stored in .js text file
function returnMyArray()
{
return ["string1", "string2", "string3", ... "stringBigNumber"];
} // eof returnMyArray()
I 'include' the external file with the usual javascript script & src tags and assign the array with something like:
myArray = returnMyArray();
I want to achieve the equivalent in c++, ie assign an array stored in a file to an array in my c++ source code so that the data is available for execution when compiled.
I suppose in theory I could copy and paste (suitable formatted) arrays from files into my c++ source code but they are too large for this to be practical.
I can easily re-write the files to whatever format would be easiest to have c++ access the data - either in c++ array syntax or one string per line to be read into an array.
In a similar vein, is there an easy way to include files containing custom function libraries when compiling with g++ in terminal? (my web searches show plenty of ways for various IDE applications but I am writing source in vim and compiling with g++ on the command line).
I am sorry if this is trivial and I have missed it but I am stumped!
Thank you.
Here's how I'd structure this:
file: 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
file: class.h
extern int myArray[]; // you should fill in the size if you can
// more stuff here
file: 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.