Somewhere in my code I use int array[L]
. I specify the array length: #define L 64
. Everything is ok. But what if I want to specify this value 64 in a (external) text file, not in the code? How can I read a text file into #define?
Asked
Active
Viewed 573 times
0

pscm
- 13
- 2
-
I wouldn't recommend defining macro values outside the source code. If you absolutely have to, you'd have to open the file read-only and parse the text file to get your value. – David Corbin Jul 22 '16 at 18:14
-
Your code would not compile since L would not pre-process to an integer litteral. By the way, a header file is an external text file. If you want dynamically sized array, this won't work. – clarasoft-it Jul 22 '16 at 18:19
-
most compilers will let you specify a Macro definition on the command line. Usually it's -D. So, in your Makefile, you'll want to read the external file, and parse out the value for L. Than specify that value as the parameter to the -D compiler flag. You will soon become a Makefile guru. Check this out: http://stackoverflow.com/questions/6767413/create-a-variable-in-a-makefile-by-reading-contents-of-another-file – bruceg Jul 22 '16 at 18:20
2 Answers
2
But what if I want to specify this value 64 in a (external) text file, not in the code?
There are two methods to set the value of a macro that I can think of.
Define it in code. A text file won't do for this purpose.
Define it as command line option in the compiler (
-DL=64
).If you use
make
, you can define the option in the appropriateMakefile
.If you use an IDE, you'll need to figure out how to do that in the various settings that IDEs provide.

R Sahu
- 204,454
- 14
- 159
- 270
0
Read the text file, and then malloc
the array:
int *array;
int L;
int main(void)
{
L = readLengthFromTextFile();
array = malloc( L );
if ( array == NULL ) {
printf( "array allocation failed\n" );
exit(1);
}
// use the array as if declared as: int array[L];
free( array );
}

user3386109
- 34,287
- 7
- 49
- 68