简体   繁体   中英

How to define common function in c

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 -eg 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 ....

Whenever I use a function more than once I consider making it part of one of my libraries, which I include as necessary in my later projects. Some functions don't make the grade, and most need to be rewritten to make them more universal and reusable. However it's worth the little bit of extra work.

Caveat: having grown up in a procedural world, I'm still using procedural library code that some day I'm going to refactor properly into objects and the like, yeah right. Translation: lugging too many libraries around for too long tends to tie you into using legacy code into current projects, unless you're marginally smarter and better disciplined than I am.

However, it's not a bad place to start. Writing reusable code and building up a repository of "written once, used often" code is a practice I heartily recommend.

Here 'sa 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM