简体   繁体   中英

Use stdlib functions without including stdlib.h

I am compiling a large number of files which use srand() and rand() without including stdlib.h. I'm aware that this is bad practice but, as I cannot change the files that I am compiling, inserting the necessary include statement in each file is not an option.

How can I configure my compiler to allow implicit inclusion of stdlib functions? Also, is there a way to implicitly use the std namespace in the same way?

Edit: Using g++

Edit: Looks like this is the answer (to the first part, at least). To compile a file as if stdlib.h is included, use the option -include stdlib.h

As you've now mentioned that you're using GCC, you can just use the -include flag. Other compilers probably have equivalents.


If you don't have such a flag for your compiler, you could use the following not-entirely-serious solution, that should work nevertheless:

nice.cc

#include <stdlib.h>
#include "naughty.cc"

(where naughty.cc is the original source file).

Of course, with a suitable build system, you could automatically generate the nice wrapper files.

Since you are already embracing bad practice, how about:

cat > foo.c << EOF
#include <stdlib.h>
#include "file-to-compile.c"
EOF

${CC} foo.c

You're using GCC, so you can use the -include option (from the manual ):

Process file as if #include "file" appeared as the first line of the primary source file.

For example:

g++ -include stdlib.h foo.c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM