I've got two c programs: program1.c and program2.c
Both of the two programs, have three or more same functions. How can I define them one time and use it inside both?
An example: I've got two programs: simple-calculator.c and scientific-calculator.c.
Both have the basic operation (Addition, Subtraction, Multiplication and Division). I want to define a thrid file "basic-operation.c" and create a function per operation, and then include these function inside both scripts.
I guess that you are on a Posix system (Linux, MacOSX...)
I assume that your two source files program1.c and program2.c corresponds to two different executables program1 and program2
Make a header file myheader.h containing types, function & variable declarations.
Make an implementation file common.c containing the common functions (and common variables) definitions
Add #include "myheader.h" inside all of program1.c, program2.c, common.c
compile common.c to an object file common.o:
gcc -Wall -g -c common.c -o common.o
compile each of program1.c and program2.c and link it to that object file common.o
gcc -Wall -g program1.c common.o -o program1
gcc -Wall -g program2.c common.o -o program2
Later, learn how to make a program library -e.g. a static library libcommon.a or a shared library libcommon.so - (read this howto) and use a builder like make (see this documentation, and also this example). Your library could contain several members common_a.o and common_b.o ....
Here's a good description. Basically, you write a third file that contains common code, and compile it into a library; you extract the signatures of those functions into a header file; you #include the header in each of your two program files; and during linking you link your new program against the compiled library.
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