Ant
Ant

Reputation: 134

Calling functions from an external C file that has its own main()

I have two C files, program.c and tests.c, that each contain a main function.

program.c is a standalone program, that compiles and run normally on its own. But I would like to also be able to use some of its functions in tests.c (without using a common header file). Is there a way of doing this?

If I insert the prototype of the function I want from program.c into tests.c and compile with:

gcc -o program.o -c program.c
gcc -o tests.o -c tests.c
gcc -o tests tests.o program.o

I obtain an error duplicate symbol _main, which I understand since there are indeed two `main' functions.

I basically would like to be able to treat program.c both as a standalone program and as a library, similarly to what could be done in Python with if __name__ == '__main__'.

Upvotes: 0

Views: 169

Answers (2)

Ant
Ant

Reputation: 134

So I managed to achieve what I wanted thanks to the comment from @pmg:

I compile program.c into a standalone binary (gcc -o program program.c), but I also compile it into an object file with "main" renamed (gcc -c -Dmain=mainp -o program.o program.c).

I can then use this object file (that does not contain a "main" symbol anymore) to compile tests.c: gcc -o tests tests.c program.o.

Thanks @pmg, I did not know this use of the -D option.

Upvotes: 0

ryyker
ryyker

Reputation: 23236

If you need to have two separate distinct executables for which some of the functionality between them is similar you can share the common functionality by placing relevant functions into a third file, and compiling as a portable executable, DLL in Windows. (or shared library in Linux.) Each of these file types contain sharable, executable code, ithout the main() function, designed to be linked during compile time, and dynamically loaded into your executable at runtime.

Here is a step by step set of instructions for shared library using GCC and Linux.
Here is a step by step example for creating DLL using GCC in windows.

Upvotes: 1

Related Questions