简体   繁体   English

自定义C库:同一库中的函数可以相互引用吗?

[英]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. 我刚刚开始创建自己的C库,以使常用函数保持整洁。 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? 最佳做法是什么?

Yes, you can. 是的你可以。

Create a header file rand_site.h and put the declaration of the function defined in rand_site.c in it. 创建一个头文件rand_site.h ,并将在rand_site.c中定义的函数的声明放入其中。

Create a header file rand_spin.h and put the declaration of the function defined in rand_spin.c in it. 创建一个头文件rand_spin.h ,并将在rand_spin.c中定义的函数的声明放入其中。

Use #include to include the two .h files in the third file, say foo.c . 使用#include将两个.h文件包括在第三个文件中,例如foo.c

Then compile foo.c and add it to the library using: 然后编译foo.c并使用以下命令将其添加到库中:

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: 如果要创建另一个具有foo.o共享库,则可以使用:

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: 如果要使用foo.o创建可执行文件,可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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