How to define common function in c - 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 -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 ....

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

Related

How to write common functions for reusing in C

I was trying to write a common function for other files could reuse it, the example as following, I have three files:
The first file: cat test1.h
void say();
The second file: cat test1.c
void say(){
printf("This is c example!");
}
The third file: cat test2.c
include "test1.h"
void main(){
say();
}
but when I ran: gcc -g -o test2 test2.c
it threw error as:
undefined reference to `say'
Additionally: I knew this would work:gcc -g -o test2 test1.c test2.c
but I don't wanna do this, because the other team would use the server, and I hope them directly use my binary code not source code. I hope that just like we use printf() function, we just need include .
You can build yourself a library from the object files containing your useful functions, and store the header(s) that describe them in a convenient location. You and your colleagues then compile with the headers and link that library with any executables that use any of those functions. That's very much the same general mechanism that the C compiler uses to include the standard headers and automatically link with the standard C library.
The mechanics vary a bit depending on platform (Windows vs Unix being the primary distinction, though there are differences between Unix platforms too), and also on the type of library (static archive vs dynamic linked / loaded libraries — also known as shared objects or shared libraries).
In broad outline, for a Unix system with a static library, you'd:
Compile library object files libfile1.o, libfile2.o, … using (for example) gcc -c libfile1.c libfile2.c.
Create an archive from the object files — using for example ar r libname.a libfile1.o libfile2.o.
Copy the headers to a standard location such as /usr/local/include.
Copy the library to a standard location such as /usr/local/lib.
You'd compile any code that uses the library functions with -I/usr/local/include (if that is not already a standard compilation option).
You'd link the programs with -L/usr/local/lib -lname (you might not need to specify -L… but you would need to specify -lname).
Including a header file does not make a function available. It simply informs the compiler that the function will be provided at a later time.
You should compile the file with the function into a shareable object file (or a library if there is more than one function that you want to share). Mind the switch -c which tells gcc not to build an executable file:
gcc -o test1.o test1.c -c
Similarly, compile the main function into its own object file. Now you or anyone else can link the object file with their main program:
gcc -o test2 test2.o test1.o
The process can be automated using make.
Other programmers can use compiled object files (`*.o') in their programs. They need only to have a header file with function prototypes, extern data declarations and type definitions.
You can also wrap many object files into the library.
On many systems you can also create the dynamic linked libraries which do not have to be linked into the executable.
you also need to compile test1:
gcc -g -o test2 test1.c test2.c.

Compiling files with own header in C

I am currently at the beginning stage of learning how to program in C, and I came across some questions regrading header files. For example
I have a header file named header.h,
which has int comp (int, int) declared in header.h and
defined in header.c
In such case, If i were to compile a test.c using the comp function, I would have to go like
gcc test.c header.c
First question: having to add header.c everytime I gcc seems too inconvenient and redundant. Is it a necessity? If not, is there a way I can get around it? If so, why? Or is it, in fact, not redundant compared to its usage, and am I just complaining?
Second question: if I were to use multiple .c files with functions declared in header.h my gcc would have to go
gcc test.c header.c header2.c header3.c .....
and that again seems too redundant. (and from hereon, same questions as First question..)
Thanks in advance. First time asking questions in SO. Please tell me if there is anyway I can improve the clarity of the question.
I think you are looking for the make, that automates the execution of the files you are compiling.
With the use of make, you don't need to write every time the commands like 'gcc test.c header1.c header2.c ...' in the terminal (if you type the commands directly to the terminal, yes, you will need to do this all the time, which is very redundant and costs lots of time). Using make, you only do this one time, and then all you have to do is run the make command.
You can see more about makefile at https://en.wikibooks.org/wiki/Make.
I hope it can help you.
You could make a shell macro or script to execute the command, if it is too much effort to use shell history feature to re-execute the command.
When your project starts to get complicated it's normal to use a build system in which you configure the build commands in the build system, and then you invoke the build system when you want to build. For example, write a Makefile that lists all the .c files using the right syntax for makefiles, and then type make each time you want to build.
You could consider using an Integrated Development Environment which is a (usually) GUI that includes a build system and other useful features, in which case you just need to hit a key to build and run.
It is often desirable to spread out your code across multiple files; this helps to ease code management. Header files provide a unified way to expose functions defined in libraries or source code files to other source code files without including the actual code for those functions. This way, the same header file can be included in multiple source code files without compiling the same code for each of those files. However, this means that the source code for functions in the header file must be given to the compiler also. As such, you have to give your header.c to the compiler each time you compile.
This does mean that you will compile header.c each time you build your project, which is a bit redundant. One way around this is to compile the header.c into an object file, and then give that the compiler when you build:
gcc -c header.c -o header.o
gcc header.o test.c
Furthermore, software developers often like to distribute their program functions to other developer but without providing the actaul code. To do this, they often use software libraries, which contain the compiled source code, along with header files to access this code. This is probably a little more than what your looking for, so I'll leave you read up on it.
All this is used not to reduce redundancy in your compiler commands, but in your compiled programs. To make programmers' lives easier building their programs, makefiles and IDEs are often used. These may be things you might have to read up on, but the other answers posted here should provide a good starting point.
Writing a simple Makefile is very useful for compiling C programs. Here's an example
CC = gcc
CFLAGS = -g -Wall
OBJECTS = main.o cfile1.o cfile2.o cfile3.o
run: $(OBJECTS)
$(CC) $(CFLAGS) -o run $(OBJECTS)
Don't worry about header files when writing a Makefile; only worry about your ".c" files. This example Makefile assumes that you want to compile main.c, cfile1.c, cfile2.c, and cfile3.c. When adding the C files to your Makefile, make sure to use ".o" instead of ".c".
The Makefile should be in the same directory as your C files and must be named "Makefile" with a capital M. Simply type "make" to compile. Then run the program with "./run".

Including header files into static library

Since every time when we link against a static library we also need to include the header files, I am wondering if it is possible to archive into the static library, when creating it, those heads?
Say I have two object files foo1.o and foo2.o generated by
gcc foo1.c -I foo1.h -c -o foo1.o
gcc foo2.c -I foo2.h -c -o foo2.o
Gcc tutorials tell us we can generate libfoo.a using
ar libfoo.a foo1.o foo2.o
This must sound silly, but is it possible to put those header files inside libfoo.a when archiving? In this way, when linking against libfoo.a, people no more need to spend hours in order to find and include foo1.h and foo2.h, so there seems to be some benefits in doing so, right?
Thanks for your ideas.
First, the header is required to compile your source, not to link it. You do not need the header to link your objects with static libraries.
Second, no, there is no standard or common way to generate an archive with both the library and it's header. Probably there is no way to do this with common C compilers.
You could declare the library's prototypes inside your source, and than ignore the header. But this would be unsafe, since there will be no guarantee that both library and you source where compiled with compatible prototypes.
Following Paul Griffiths comments. If you just want to not have to include a path for every library, you should install those headers and those libraries and set the path in you environment.
Example:
export C_INCLUDE_PATH=$HOME/install/include
export LIBRARY_PATH=$HOME/install/lib
You must export this every time you open an new shell, or you can define it in you .bashrc
You can compile everything you want into a static library, but the counterpart is that you won't be able to call the functions from outside (ie by linking) because if you want to do so, you'll always need their prototypes

What is a multiple compilation, how is working and why i should use it?

I am learning C and I just read the term multiple compilation.Till now I had a single file.c and I used the command gcc file.c to compile it and then ./a.out to execute it. But I got confused a little bit. When should I use the multiple compilation instead of the single and which would be the possible reasons that they will lead me to prefer a multiple compilation instead of the single? I searched it and I found some articles but they didn't cover fully my questions. 1 (this is for c++) , 2If i undestood well if I have some files.c in my project eg file1.c, file2.c and then i want to link them, i execute
gcc file1.c
gcc file.c
gcc file1.o file2.o //somehow i have to create the .o files..
Thank you..
Compilation takes time. There's no point in re-compiling C code that hasn't changed. So, for large projects, it makes sense to split the code into multiple files (typically not randomly of course, but into modules of different functionality) and compile them only when needed.
Linking is the process of taking a bunch of object code (what the .o files are called) and turning them into a single program.
There are many steps to compiling.
When you invoke gcc it will create by default an executable file i.e. all steps in one go:
.c -> .i preprocessor
.i -> .s compiler
.s -> .o assembler
*.o -> a.out linker
Generally the first two take up the most time. If you have a large project then recompiling the entire project may take a lot of time when you are developing. So the compiler allows you to stop at a certain point and reuse previous results of files that have not changed:
gcc -E for preprocess only (rarely used)
gcc -S compile, but don't assemble. Useful for debugging or optimising assembly
gcc -c compile, assemble, but don't link. This is the most commonly used one and produces object files. Those contain your assembled functions (object code), but it's not capable of running because not all functions may be present yet, library functions are missing and the executable header has not been linked in.
The final step gcc -o executable *.o will then take all those and link them together to create an executable. Optionally linking libraries into it.
Generally having all functions in one source file will allow the compiler to do the more optimisations (i.e. inlining), but at the cost of compile time.
Have a look at https://cs.senecac.on.ca/~btp200/pages/images/compile_link.png

Which way should I compile my C code?

I have three files, test.c, foo.c, foo.h.
In foo.c i
#include "foo.h"
In test.c i
#include "foo.c."
Then when I compile my code, I use gcc -o test test.c, and it compiles.
However, my professor told me, I should use
#include "foo.h"
inside my test.c rather than #include foo.c, and I should compile it this way
gcc -o test test.c foo.c
Is the second way more preferred? If it is, why? What's the difference between these two compilation?
In most cases you should never include source files (apart from cases where you would probably want to include a piece of code generated dynamically by a separate script). Source files are to be passed directly to the compiler. Only header files should be included.
Although the way that your professor suggests is correct, the following way has more educational value in this case:
gcc -c test.c
gcc -c foo.c
gcc -o test foo.o test.o
The first two lines compile each source file to an object file, and the third line doesn't really compile but only invokes the linker to produce an executable out of the 2 object files. The idea is to make a distinction between compiling and linking, which would be performed transparently in the way your professor suggests.
The major reasons not to #include .c files in other .c files are:
Avoid duplicate definition errors: suppose foo.c defines the function foo(). You have two other files that use foo(), so you #include "foo.c" in both of them. When you try to build your project, the compiler will translate foo.c multiple times, meaning it will see multiple attempts to define the foo function, which will cause it to issue a diagnostic and halt.
Minimize build times: even if you don't introduce duplicate definition errors, you wind up recompiling the same code needlessly. Suppose you #include "foo.c" in bar.c, and you discover you need to make a one-line change in bar.c. When you rebuild, you wind up re-translating the contents of foo.c unnecessarily.
C allows you to compile your source files separately of each other, and then link the resulting object files together to build your applications or libraries. Ideally, header files should only contain non-defining object declarations, function prototype declarations, type definitions, and macro definitions.
It is common practice to #include header files instead of source files, and compile source files individually. Separation of concerns makes it easier to work with in large projects. In your example, it may be trivial, but could be confusing when you have hundreds of files to work with.
Doing it the way your professor suggests means you can compile each source separately. So, if you had a large project where the sources were thousands of lines of code, and you changed something in test.c, you can just recompile test.c instead of having to recompile foo.c along with it.
Hope this makes some sense :)
If you want to compile several files in gcc, use:
gcc f1.c f2.c ... fn.c -o output_file
Short answer:
YES the second way is more preferred.
Long answer:
In this specific case you will get the same result.
To have a dipper understanding you need first to know that "#include" statement basically copy the file it's include and put its value instead of the "#include" statement.
Therefore "h" files are used for forward declaration which you have no problem several different file will include.
while "c" files have the implementations, in that case if both files will implement the same function you will have error in linking them.
Lets say you would have "test2.c" and you will also include foo.c and try to link it with the test.c you will have two implementations of foo.c. But if you only include foo.h in all 3 files (foo.c, test.c and test2.c) you can still link them cause foo.h shouldn't have any implementations.
It is not good practice to include .c files.
In your case
Include foo.h in both test.c and foo.c , but add this inside your header file
#ifndef foo.h
#define foo.h
..your header code here
#endif
Writing the header the above way , ensures that you can include it multiple times , just to be on the safe side.
Coming to how you must put your code in files>
In foo.h
You place all your global structures ,and variables along with function prototypes , that you will use.
In foo.c
Here you define your modular functions
In test.c
Here you generally have your main() , and you will call and test the functions defined in foo.c
You Generally put all the files in the same folder , and the compiler will find them and compile them individually , they will be connected later by the linker.
gcc f1.c f2.c ... fn.c -o output_file

Resources