Search code examples
cgccloggingc-preprocessoruart

Replacing macros during compile process


My project uses a logging mechanism, which is basically a call to a macro in each of my components.

Behind the macro is a function call, which is used to write the log using a slow line like UART.

Example:

LOG("An error has occurred. Please check XYZ. Code: %d", errorcode) 

Instead of writing the whole text to UART, I want to replace every occurrence of LOG like this:

LOG("12345 %d", errorcode) 

Each call to LOG must be replaced by a short version, where the text is replaced by a unique number. The dynamic part may not be replaced. The mapping of the unique number to the original text must be placed into a file. Something like this:

12345:"An error has occurred. Please check XYZ. Code:"

At the other end of the UART a log reader has to read this mapping file to make it human readable.

The advantage is that this is perfect for low bandwidth.

My question : How can I do this while compiling my code? I am using gcc and working on a Linux environment. I assume that the preprocessor has to handle this. Or a kind of pre-script? Or is there a better way of doing this?


Solution

  • You are most assuredly going to need a pre-processing script for this. The power of the C preprocessor is quite limited -- pretty much it is limited to simple text substitution. If all your LOG calls are on 1 line each, and none of their messages contain parens, then you can probably do it with a fairly simple text processing tool, perhaps awk. If not, I would use a programming language, perhaps perl, to construct it.

    I am assuming there are a great number of these LOG calls in your program -- otherwise simply editing the program might make more sense.