How to Write C Program Without Header File

Generally, in every C program, we include at least one header file stdio.h. The functions like printf and scanf, which we are regularly using in our program, are defined inside stdio.h header file. So the purpose of including stdio.h is to add the definition of these functions into our program. Now, can we write any program for example, hello world program without using a header file? It is a quite interesting question and asked many times by interviewers, to confuse at the same time to test the understanding of the candidate about his/her knowledge in C.

When we compile any program then firstly, C preprocessor expands all header files into a single file, then later compiler compiles the expanded file. Using the advantage of C preprocessor we can extract the declaration of printf function from the header file and use it directly in our program.

We can write any program without using the header file, but we have to manually put the stuff in our source files.

Hello world Program in C without using the header file

int printf(const char *format, …);
int main()
{
  printf("Hello, World!\n");
  return 0;
}

Output:-

Hello, World!

This program doesn’t give any warning and error. This is also a solution to our question. Declaration of the printf function is directly used in the program.

We can also declare printf function inside the extern keyword. Here the extern keyword tells the compiler that the declaration of the printf function is somewhere in C. So, the compiler will find the printf declaration file and include it into our program.

extern "C"
{
   int printf(const char *format, …);
}
int main()
{
   printf("Hello, World!\n");
   return 0;
}

Output:-

Hello, World!

Compile this program with the C++ compiler and execute it.

Apart from the above ways, there is also a small trick. The trick is:- Write a program without using any header file and save it using the .c extension. Now, compile and run the program.

int main()
{
   printf("Hello, World!\n");
   return 0;
}

Output:-

Hello, World!

This program will give warnings but run successfully. When we add .c extension to the file then by default compiler include all necessary file to the program and finally, our program runs successfully. Remember that it is a trick, not a concept. So it better to use the header file in the C program for solving the big problems.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *