Is there a portable way to print a message from the C preprocessor?

PrintingC Preprocessor

Printing Problem Overview


I would like to be able to do something like

#print "C Preprocessor got here!"

for debugging purposes. What's the best / most portable way to do this?

Printing Solutions


Solution 1 - Printing

The warning directive is probably the closest you'll get, but it's not entirely platform-independent:

#warning "C Preprocessor got here!"

AFAIK this works on most compilers except MSVC, on which you'll have to use a pragma directive:

#pragma message ( "C Preprocessor got here!" )

Solution 2 - Printing

The following are supported by MSVC, and GCC.

#pragma message("stuff")
#pragma message "stuff"

Clang has begun adding support recently, see here for more.

Solution 3 - Printing

You might want to try: #pragma message("Hello World!")

Solution 4 - Printing

Most C compilers will recognize a #warning directive, so

 #warning "Got here"

There's also the standard '#error' directive,

 #error "Got here"

While all compilers support that, it'll also stop the compilation/preprocessing.

Solution 5 - Printing

#pragma message("foo")

works great. Also wouldn't stop compilation even if you use -Werror

Solution 6 - Printing

Another solution is to use comments plus a shell script to process them. This takes some discipline (or a shell script which catches typos).

For example, I add comments formatted //TODO and then a shell script which collects all of them into a report.

For more complex use cases, you can try to write your own simple preprocessor. For example, you could edit your sources as *.c2 files. The simple preprocessor would read the source, look for //TODO, and write printf("TODO ...") into the output *.c file.

Solution 7 - Printing

You can't. Preprocessors are processed before the C code. There are no preprocessor directives to print to the screen, because preprocessor code isn't executed, it is used to generate the C code which will be compiled into executable code.

Anything wrong with:

#ifdef ...
printf("Hello");
#endif

Because this is all you can do as far as preprocessors go.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew WagnerView Question on Stackoverflow
Solution 1 - PrintingYouView Answer on Stackoverflow
Solution 2 - PrintingMatt JoinerView Answer on Stackoverflow
Solution 3 - PrintingRuelView Answer on Stackoverflow
Solution 4 - PrintingnosView Answer on Stackoverflow
Solution 5 - PrintingMartinView Answer on Stackoverflow
Solution 6 - PrintingAaron DigullaView Answer on Stackoverflow
Solution 7 - PrintingAlexander RaffertyView Answer on Stackoverflow