KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I want to write a macro to write a string, using the compile-time optimisation of knowing the length of a string literal. But I need to detect misuse, using pointers. Here's what I mean: void transmit(const char *data, int length); #define tx_string(x) transmit((x), sizeof(x) -1) void func(char *badmsg) { tx_string("GO"); // ok tx_string(badmsg); // not OK } With the second call, the size will be nonsense (sizeof a pointer). I want to produce a compile-time error if I attempt to use tx_string on anything other than a string literal. This is using gcc; is there some gcc thing I can use to do this? Edit: I work with data buffers that may contain nulls or not be terminated by nulls. I REALLY want to prevent pointers being used for this, and prevent run-time strlen() use. Edit 2: Here's an example which would cause a problem. I'll invent an imaginary protocol where I have to tell a 16-bit microcontroller an address using the command GO followed by an address as 16-bit raw (two 8-bit characters), and I want to go from address 0. #define GOSEQ "GO\000\000" void func(void) { char *bad = GOSEQ; tx_string(GOSEQ); // ok, sends 4 bytes: GO and two zero bytes tx_string(bad); // bad, using runtime strlen sends two characters "GO" } I feel sure there must be some kind of gcc builtin check for this. I see the Linux kernel sources using compile-time distinction tricks like this a lot.. but can't lay my hands on a specific one quickly. So far "Windows programmer"'s idea looks good, but a more meaningful compile-time error would be a bonus.
Tags (comma-separated)
Save Edits
Cancel