Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid standard include files during compilation

Tags:

c++

c

I am trying to use my own printf function so i don't want to include standard include files... so I am compiling my code with -nostdinc

I have created my program something like this:

extern int printf(const char*,...);
printf("Value:%d",1234);
//printf("\n");

It is working fine for this code, but when I use printf("\n") then it is showing undefined reference to 'putchar'.

If i comment printf("\n"); then nm command is showing

$ nm test1.o
         U exit
00000000 T main
         U printf
00000030 T _start

but if I use printf("\n"); then nm command is showing

$nm test1.o
         U exit
00000000 T main
         U printf
         U putchar
0000003c T _start

I am not getting how and from where putchar is getting included

gcc version 4.8.2 (GCC)

like image 412
rajenpandit Avatar asked Jun 29 '14 07:06

rajenpandit


People also ask

Does order of include files matter?

Does the include order matter? If your header files are self-contained, then the include order technically shouldn't matter at all for the compilation result. That is, unless you have (questionable?) specific design choices for your code, such as necessary macro definitions that are not automatically included.

Do I need to compile header files?

You don't need to compile header files. It doesn't actually do anything, so there's no point in trying to run it. However, it is a great way to check for typos and mistakes and bugs, so it'll be easier later.

Do header files need to be in the same directory?

No. Usually you give the compiler (or, more specifically, the preprocessor) a bunch of include directories, to tell it where to look for header files. This is typically done from the Makefile (or from the project settings when building inside an IDE).

Which header do you need to include in order to use standard C++?

In C++ program has the header file which stands for input and output stream used to take input with the help of “cin” and “cout” respectively. There are of 2 types of header file: Pre-existing header files: Files which are already available in C/C++ compiler we just need to import them.


1 Answers

gcc optimizes printf in certain situations. You can look at the function fold_builtin_printf here for the complete details. IIRC, it optimizes calls with one argument followed by a newline to puts/putchar. You can turn it off by specifying -fno-builtin(gcc docs).

like image 67
Pradhan Avatar answered Sep 25 '22 19:09

Pradhan