This is a silly question, but I can't seem to get it right. I came across another question, but the answer given doesn't properly address the warnings in my specific use case.
I'm trying to declare an array of constant strings to pass as argv
in posix_spawn
function, but GCC complains about const
being discarded. See a sample code below:
#include <stdio.h>
/* Similar signature as posix_spawn() shown for brevity. */
static void show(char *const argv[])
{
unsigned i = 0;
while(argv[i] != NULL) {
printf("%s\n", argv[i++]);
}
}
int main(void)
{
const char exe[] = "/usr/bin/some/exe";
char *const argv[] = {
exe,
"-a",
"-b",
NULL
};
show(argv);
return 0;
}
And compile it as:
gcc -std=c89 -Wall -Wextra -Wpedantic -Wwrite-strings test.c -o test
test.c: In function ‘main’:
test.c:17:9: warning: initializer element is not computable at load time [-Wpedantic]
exe,
^
test.c:17:9: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
test.c:18:9: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
"-a",
^
test.c:19:9: warning: initialization discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
"-b",
^
Since, exe
is itself a constant string like "-a"
and "-b"
, I thought it's correct. But GCC seems to disagree. Removing exe
from the array and removing -Wwrite-strings
compiles without warnings. Maybe I am missing something too basic.
How does one declare a const array of strings?