Building a static library

We will build a static library, libhelloworld, from two source files, hello.c and world.c, and use it to build a hello world application. The source files for the library are presented here. The following is the code for the hello.c file:

char * hello (void) 
{ 
  return "Hello"; 
} 

This is the code for the world.c file:

char * world (void) 
{ 
  return "World"; 
} 

To build the library, follow these steps:

  1. Configure the build environment:
$ source /opt/poky/2.4/environment-setup-cortexa9hf-neon-poky-linux-gnueabi
  1. Compile and link the library:
$ ${CC} -c hello.c world.c
$ ${AR} -cvq libhelloworld.a hello.o world.o
  1. Verify the contents of the library:
$ ${AR} -t libhelloworld.a

The application source code is presented next:

  • For the helloworld.c file, the following is the code:
#include <stdio.h> 
#include "helloworld.h" 
 
int main (void) 
{ 
  return printf("%s %s
",hello(),world()); 
} 

With the helloworld.h header file being the following:

#ifndef HELLOWORLD_H                                                             
#define HELLOWORLD_H                                                             
char * hello (void);                                                             
char * world (void);                                                             
#endif 
  • We now build it indicating where to find the static library (inside libs/) and the include file (inside inc/) to the compiler:
$ ${CC} -o helloworld helloworld.c -l helloworld -L libs/ -I inc/
  • We can check which libraries it links with using readelf:
$ readelf -d helloworld 
Dynamic section at offset 0x534 contains 24 entries:
Tag Type Name/Value

0x00000001 (NEEDED) Shared library:
[libc.so.6]
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset