开发者

How to use functions in a .a (static library) file in C?

开发者 https://www.devze.com 2022-12-27 05:59 出处:网络
I have a static library project in Eclipse that was compiled into a .a file. So now how would I use the functions and constants in that library? Would I just put in into my includes:

I have a static library project in Eclipse that was compiled into a .a file. So now how would I use the functions and constants in that library? Would I just put in into my includes:

#include "mylib.a"
开发者_运维知识库


The static library would be included in the linking process, not in the source code. The library should have an associated .h header file containing the function definitions and constants that you would #include in your source code. Something like

#include "mylib.h"

Then you would compile the source and link it with mylib.a to produce the final binary.


  1. Include the library headers in (your) files.
  2. Then while building your executable, add the location of the library's header files to your compiler's include path and then link against the static library. As in

    gcc -I/Directory path where mylib header files are located/ foo.c bar.c /Directory where mylib archive is located/mylib.a

Here foo.c and bar.c are files containing your code.


library implementation.

/* Filename: lib_mylib.c */
#include <stdio.h>
void fun(void)
{
  printf("fun() called from a static library");
}

library header.

/* Filename: lib_mylib.h */
void fun(void);

Compile library files.

gcc -c lib_mylib.c -o lib_mylib.o 

Create static library. This step is to bundle multiple object files in one static library.

ar rcs lib_mylib.a lib_mylib.o 

driver program.

/* filename: driver.c  */
#include "lib_mylib.h"
void main() 
{
  fun();
}

Compile the driver program.

gcc -c driver.c -o driver.o

Link the compiled driver program to the static library. Note that -L. is used to tell that the static library is in current folder.

gcc -o driver driver.o -L. -l_mylib

Run the driver program

./driver 
fun() called from a static library

Reference: https://www.geeksforgeeks.org/static-vs-dynamic-libraries/

0

精彩评论

暂无评论...
验证码 换一张
取 消