use and create library in c

Table of Contents

Convention in C: lib.h contains signatures of functions and defs/typedefs some variables. lib.c contains at least implementations of those functions. For other programs client.c that want to use this library, it can only access functions and variables defined in lib.h1, which make sense as only those definition are in the header file lib.h and copied to the start of client.c at compile time

Interesting experiment: instead of using lib.h, copy and paste its content directly into lib.c and client.c, compile them seperately, and see if you can use function defined in lib.c, compiled to lib.a or lib.so in client.c.

1. Writing the library

#ifndef lib_h_
#def lib_h_
#define MAX_FOO  20

// a type definition exported by library:
struct foo_struct {
    int x;
    float y;
};
typedef struct foo_struct foo_struct;

// a global variable exported by library
// "extern" means that this is not a variable declaration, it
// just defines that a variable named total_foo of type int
// exits and you can use it (its declaration is in some library source file)
extern int total_foo;

// a function prototype for a function exported by library:
extern int foo(float y, float z);   // a very bad function name

#endif
  • constants, struct and typedef (that are used in the program and you’ll need to use to pass argument to the library functions)
  • typically, variables used by library functions, like “global offset”.
  • how to call a library function
  • all variables and functions here (without any implementation) need the keyword extern. This keyword sort of registered the variables and functions here so that the compiler would know how to find them. both lib.c and your application app.c would include this lib.h, meaning identical extern int total_foo; would appear in both.

1.1. compiling object files

1.2. static library with multiple object files

1.3. dynamic library with multiple object files

2. using the library in application

you application would be a c source file like app.c

#include "lib.h"
int main (){
    total_foo = 2;
    foo(1.1, 2.2);
}
  • use the variables directly.(don’t do int total_foo = 2;, would report error)

3. compiling application with library

3.1. compiling with object file library

3.2. compiling with static library

3.3. compiling with dynamic library

4. reference

largely refered to this tutorial

Backlinks

Footnotes:

1

lib.c by the time other program wants to use it would be compiled to binary(.so shared object file or .a archive file) already like that lots and lots of .so files you can find on your system with find /usr |grep \\.so$

Author: Linfeng He

Created: 2024-04-03 Wed 23:21