Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile C source code without a main function?

Tags:

c

How can I compile my C source files without needing to put a main function within them?

I get an error for the .cfiles that have no main function and don't want to have to add the main function just for compilation.

like image 852
some_id Avatar asked Apr 23 '11 12:04

some_id


People also ask

Can I compile C program without main ()?

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.

Can we run program without a main () function?

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.

Is main () function mandatory in C?

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.

Do all C files need a main function?

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.


2 Answers

On GCC, the -c switch is what you want.

-c means "compile, don't link", and you get a name.o output file.

like image 181
Kos Avatar answered Sep 22 '22 20:09

Kos


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.

like image 24
Vignesh Avatar answered Sep 23 '22 20:09

Vignesh