Steckdoose
Steckdoose

Reputation: 23

Ignore macro if it is not defined

I am using the following macro in some C files:

DBGL_LOG_INFO(DBGL_UART_LOG_ENABLED, "UART is initialized");

The macro calls my logging module, if the define LOG_UART_ENABLED is true. If the define is false, the logging code will not be compiled and so does not influence my regular program code in release build.

But now, I have the following Problem: The C files, which does contain this macro call should be also used in another project, where the log module does not exist. So the define DBGL_UART_LOG_ENABLED also does not exist in this other Project.

Of course, when I compile the file with this code in the project, i get the following error:

'DBGL_UART_LOG_ENABLED' undeclared (first use in this function); did you mean '...'?

Is it possible, to tell the compiler, that this code should be ignored, if the macro and the defines are missing?

Thank you in advance.

Upvotes: 0

Views: 950

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 546153

Conditionally define the macro. For instance, the following is a common pattern:

#ifndef DBGL_UART_LOG_ENABLED
#   define DBGL_UART_LOG_ENABLED 0
#endfif

And you probably also need to handle DBGL_LOG_INFO:

#ifndef DBGL_LOG_INFO
#   define DBGL_LOG_INFO(...) do {} while (false)
#endif

This defines the macro as an empty block that swallows its arguments. That way, you can continue to use the macro in code without it affecting the output.

Upvotes: 2

Lundin
Lundin

Reputation: 215350

This would be why such code is commonly written as

#ifdef DBGL_UART_LOG_ENABLED

/* do stuff with DBGL_UART_LOG_ENABLED */

#endif

Upvotes: 1

Related Questions