oLas
oLas

Reputation: 1241

Custom C library: can functions in the same library refer to each other?

I've just started to create my own C libraries to keep my commonly used functions tidy. However, I've hit a new problem and I struggled to find information on the best route to take.

I generate my library of two functions using the following:

gcc -I. -c -fpic rand_site.c
gcc -I. -c -fpic rand_spin.c
gcc -shared -o libstatphys.so rand_site.o rand_spin.o

Each of these source files contained a single function. I was hoping to create a third function for my library that uses the two functions above but I'm not sure how to use functions from within the same library.

Am I going about this the right way? What is the best practice for doing this?

Upvotes: 0

Views: 419

Answers (1)

R Sahu
R Sahu

Reputation: 206567

Yes, you can.

Create a header file rand_site.h and put the declaration of the function defined in rand_site.c in it.

Create a header file rand_spin.h and put the declaration of the function defined in rand_spin.c in it.

Use #include to include the two .h files in the third file, say foo.c.

Then compile foo.c and add it to the library using:

gcc -I. -c -fpic foo.c
gcc -shared -o libstatphys.so rand_site.o rand_spin.o foo.o

If you would like to create a second shared library that has foo.o, you can use:

gcc -I. -c -fpic foo.c
gcc -shared -o libfoo.so foo.o -lstatphys

If you would like to create an executable using foo.o, you can use:

gcc -I. -c foo.c
gcc foo.o -lstatphys

Upvotes: 3

Related Questions