I want to get rid of compiler warnings when calling certain C functions from C++.
Given the following function in a C library:
void log_something(char * message);
It is used in both C and C++ code. When called with a string literal, the C compiler thinks everything is peachy. The C++ compiler gives this stern warning but produces a binary:
log_something("This is a log message");
WME.cpp:7:35: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
If instead of a string literal or a char *
I pass a char const *
, I get a warning from the C ompiler and an error from the C++ compiler.
MWE.c:9:19: warning: passing argument 1 of ‘log_something’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
MWE.cpp:11:19: error: invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
Assuming I have verified that log_something(message)
does not modify *message
in any way, is it safe to change the function to take a char const *
instead of a char *
?
Existing C and C++ code must continue to work without modification after the function is changed (re-compiling for updated library is allowed, but nice if it can be avoided).
Simple tests suggests it should work, but I'm worried there might be an edge case I haven't thought about.
Aucun commentaire:
Enregistrer un commentaire