Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Print \"Hello World\" in C/C++ without using header files
In C/C++, we typically use header files to access standard library functions. The printf() function is declared in the "stdio.h" header file and is used to print data to the console. However, it's possible to print "Hello World" without including any header files by declaring the function prototype ourselves.
Syntax
int printf(const char *format, ...);
Method 1: Using printf() Declaration in C
In C, we can declare the printf() function prototype directly in our program without including stdio.h. The compiler will link to the standard library automatically −
int printf(const char *format, ...);
int main() {
printf("Hello World<br>");
return 0;
}
Hello World
Method 2: Using syscall() in C++ (Linux Only)
In C++, we can use system calls directly to write to stdout without header files. This method uses the write system call −
Note: This method works only on Linux/Unix systems and requires knowledge of system call numbers.
extern "C" long syscall(long number, ...);
int main() {
const char* msg = "Hello World<br>";
syscall(1, 1, msg, 12); // write syscall: write(1, msg, 12)
syscall(60, 0); // exit syscall: exit(0)
return 0;
}
Hello World
How It Works
- In Method 1, we manually declare
printf()with the correct signature. The linker finds the actual implementation in the C standard library. - In Method 2,
syscall(1, 1, msg, 12)calls thewritesystem call where: 1 = write syscall number, 1 = stdout file descriptor, msg = message pointer, 12 = byte count. - The
syscall(60, 0)calls theexitsystem call to terminate the program cleanly.
Key Points
- Method 1 is portable and works on all C compilers.
- Method 2 is system-specific and only works on Linux/Unix systems.
- Both methods avoid including any header files but still rely on system libraries.
Conclusion
While it's possible to print "Hello World" without header files, using standard headers like stdio.h is the recommended practice. These techniques demonstrate how function declarations and system calls work under the hood.
