1

Context: Long time programmer, coming back to C as a baby. Apologies for what are probably obvious to you questions.

Can I apply macros to a C program without compiling it?

My understand of C Macros: They process your source file before handing it off to be compiled

Me: Here's my file
Compiler: OK, let me apply the macros get something I can compile
Compiler: OK, macros applied, lets compile this

Is there a way to view the program file that's actually passed off for compilation? i.e. a way to apply the macros but not compile the program.

For example, I have a small program that uses the PRIxPTR macro.

#include <stdio.h>
#include <stdint.h>

//needed for the PRI*PTR Macros
#include <inttypes.h>

int main()
{
    int i = 42;
    int* pI = &i;

    printf("iP points to address (base 16): %" PRIxPTR "\n", (uintptr_t) pI);         
    printf("iP points to address (base 10): %" PRIdPTR "\n", (uintptr_t) pI);                 
}

Compiling and running the program

$ cc main.c; ./a.out

produces the following output

iP points to address (base 16): 7fff545f587c
iP points to address (base 10): 140734608922748    

I would like to see the C source that PRIxPTR macro actually produces.

This seems like it would be possible -- is it? If not, is my understanding of macros incorrect? Or is there something else that prevents this from happening?

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
  • 1
    Dup of https://stackoverflow.com/questions/985403/seeing-expanded-c-macros – Zakir Jun 14 '17 at 19:57
  • 1
    At least some IDEs can expand individual macro invocations for you too. I know Eclipse/CDT does this when you hover the pointer over one. Note that the expansion could differ if the IDEs environment and options are different from that of the compiler. – Fred Larson Jun 14 '17 at 20:08
  • 1
    "Can I apply macros to a C program without compiling it?" - sure. The C **pre**processor can be run before the compiler. – too honest for this site Jun 14 '17 at 20:40

1 Answers1

3

If you're using gcc, use the -E option. That will generate the preprocessor output to stdout.

gcc -E -o src_pp.c src.c

Contents of src_pp.c:

# 1 "src.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "src.c"
# 1 "/usr/include/stdio.h" 1 3 4

...

# 6 "src.c" 2

int main()
{
    int i = 42;
    int* pI = &i;

    printf("iP points to address (base 16): %" "l" "x" "\n", (uintptr_t) pI);
    printf("iP points to address (base 10): %" "l" "d" "\n", (uintptr_t) pI);
}
dbush
  • 205,898
  • 23
  • 218
  • 273