How can I compile my C source files without needing to put a main
function within them?
I get an error for the .c
files that have no main function and don't want to have to add the main function just for compilation.
The answer is yes. We can write program, that has no main() function. In many places, we have seen that the main() is the entry point of a program execution. Just from the programmers perspective this is true.
Yes, we can execute a java program without a main method by using a static block. Static block in Java is a group of statements that gets executed only once when the class is loaded into the memory by Java ClassLoader, It is also known as a static initialization block.
No, the ISO C standard states that a main function is only required for a hosted environment (such as one with an underlying OS). For a freestanding environment like an embedded system (or an operating system itself), it's implementation defined.
c file and each function declaration in an own . h , that definitely does not need to be either. It even would confuse you all the way up. You actually can do so, but it is definitely not recommended.
On GCC, the -c
switch is what you want.
-c
means "compile, don't link", and you get a name.o
output file.
Suppose you have hello.c:
#include<stdio.h> #include<stdlib.h> _start() { exit(my_main()); } int my_main() { printf("Hello"); return 0; }
Compile as:
gcc -nostartfiles hello.c
and you can get an executable out of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With