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?
constin any way so it is not clear why you have linked it-Werror, it fails with errors instead.constin C. The code was correct. You see warnings because you use the switch-Wwrite-stringswhich intentionally produces warnings for correct code.-fwritable-stringsis also used. But you're right, the standard doesn't specify such a behaviour though. Corrected my question's wording. Thanks.constqualifier. It is just undefined behaviour with no diagnostic to write them, in Standard C. The-Wwrite-stringsattempts to catch write attempts, but also gives false positives when you need to call an API that isn't const-correct