Print “Hello World” in C/C++ without using any header file

1.9

Write a C/C++ program that prints Hello World without including any header file.

Conceptually it’s seems impractical to write a C/C++ program that print Hello World without using a header file of “stdio.h”. Since the declaration of printf() function contains in the “stdio.h” header file.

But we can easily achieve this by taking the advantage of C pre-processor directives. The fact is at the time of compiling a program, the first phase of C preprocessing expands all header files into a single file and after that compiler itself compiles the expanded file. Therefore we just need to extract the declaration of printf() function from header file and use it in our main program like that:-

  • C language: Just declare the printf() function taken from “stdio.h” header file.
    //Declare the printf() function
    int printf(const char *format, ...);
    
    int main()
    {
      printf( "Hello World" );
      return 0;
    }
    
    Output: Hello World
  • C++ language: We can’t directly put the declaration of printf() function as in previous case due to the problem of Name mangling in C++. See this to know more about Name mangling. Therefore we just need to declare the printf() inside extern keyword like that:-
    //Declare the printf() function inside
    //extern "C" for C++ compiler
    extern "C"
    {
    int printf(const char *format, ...);
    }
    
    int main()
    {
      printf( "Hello World" );
      return 0;
    }
    
    Output: Hello World

See this to know more about all phases of compilation of C program.

This blog is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.9 Average Difficulty : 1.9/5.0
Based on 12 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.