Skip to content
Advertisement

How to use an API in c using linux distro: ubuntu 16.04 [closed]

I am beginner in linux and I want to use an API in C language from a certain package. This package has files .h (which contain the prototypes and some defines for using the API) and .so files, as well as .dll for Windows. But I don’t know how to manipulate them in order to use properly this API in a single code.

Advertisement

Answer

There are two things you need to do:

  1. Include the correct headers for the API.
  2. Link to the shared object.

For example, to use libconfig:

main.c

#include <libconfig.h>

int main(int argc, char * argv[])
{
  config_t cfg;

  config_init(&cfg);
  config_read_file(&cfg, "example.conf");

  return 0;
}

The included header defines the API prototype, but doesn’t do the actual linking, for that you need to tell the compiler to link to the library.

gcc main.c -o main -lconfig

This process will vary depending on the library you intend to use, for most you can use the pkg-config utility these days to provide the correct include and linker options for the compiler, for example:

pkg-config --cflags libconfig
pkg-config --libs libconfig

The CFLAGS and LIBS are seperate as usually you will want to compile object files and then link, for example:

gcc -c $(pkg-config --cflags libconfig) main.c -o main.o
gcc main.o -o main $(pkg-config --libs libconfig)

Note: libconfig doesn’t have any CFLAGS, but most libraries do, these will usually be the path to their headers.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement