0

I want to get rid of compiler warnings when calling certain C library functions from C++. I know how. The question is, is it safe? The library is also used by other code.

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 compiler 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.

Åsmund
  • 1,122
  • 1
  • 12
  • 22
  • There are no edge cases. If this `log()` function did, indeed, try to modify the passed-in string, then by the virtue of it now being a pointer to a `const char` both C and C++ compilers will give you a very loud complaint. – Sam Varshavchik Feb 21 '21 at 18:37
  • Assuming you don't ever modify `*message` as you say, I would fully endorse making it `const`. – Christian Gibbons Feb 21 '21 at 18:37
  • 4
    change it to `void log_something(const char * message)` – Morpheus Feb 21 '21 at 18:38
  • `inline void thunk_log_something(char const* message) { log_something(const_cast(message); }` – Eljay Feb 21 '21 at 20:04
  • @Eljay although you then have to deal with the differing behaviours of `inline` between the two languages – M.M Feb 21 '21 at 23:55

0 Answers0