10

I need to include a #define at the top of around 300 .c files. I would prefer not to change the code as it is open source code but if I have to I will just write a script to modify all the files. Is there a way using gcc to add a #define or header file include to the top of every source file during compilation? The #define is this:

#define malloc MYmalloc
DrummerB
  • 39,814
  • 12
  • 105
  • 142
Will Brode
  • 1,026
  • 2
  • 10
  • 27

3 Answers3

25

You can pass -Dmalloc=MYmalloc to the gcc options.

For more information about the -D option:

http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html

Note that if you want to modify the behavior of malloc function for debugging purposes, you may also be interested in glibc malloc hooks:

http://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Thanks ouah, I'll try this out and I think it will solve my problems. I know about the malloc hooks and LD_PRELOAD solutions but they aren't suitable to my situation. Either way its good to mention it for other viewers. – Will Brode Oct 29 '12 at 20:30
7

gcc option -D:

-D name
    Predefine name as a macro, with definition 1.

-D name=definition
    ....

so, in your case, gcc ... -Dmalloc=MYmalloc

joe
  • 617
  • 7
  • 22
0

If you strive for redirecting malloc() calls to a custom function I would rather recommend to provide your custom code via pre-loading of your implementation at runtime. See this question for details.

Community
  • 1
  • 1
grundprinzip
  • 2,471
  • 1
  • 20
  • 34