Precompiled libraries how to

Example Description:

Demonstrate how to build a precompiled library (in library/ folder) and then use it in an integration application.

How to build:

First, the library must be built. To start, we need to move into the library folder (cd library).

Once there, build as any application, and then call the install target:

cmake -B build
cmake --build build
cmake --build build -t install

Note

Libaries can not be ran, only built. But it is possible to add a mode in CMakeLists.txt to also build a test program to test said library as an example. Albeit, using a test subfolder and CMakeLists.txt is the recommended approach.

Now, come back to the integration app folder: cd ... Now that we are in integration app, simply build and run as usual:

cmake -B build
cmake --build build
cmake --build build -t run

How to reuse for your code:

Note

Nothing used to build precompiled libraries here is particular to GAP SDK.

In order to build a precompiled/shareable library, a few important points must be respected:

  • The code must be freestanding, save for SDK’s provided code.

  • Headers must be properly separated from sources which will not be provided to clients

  • Compiled mode CMakeLists of the library must not include SDK macros directly (setupos etc)

Now, we may observe there are two CMakeLists.txt in this project: one in integration app, and one in the library. The one in library folder has two roles, one is to allow actually building from source, the other is to allow top level integration app to include its precompiled from. To do so, it has a simple if(PRECOMPILED_LIB) branch. If precompiled mode is not enabled, everything proceed as for any normal app, except for the targets being of library type instead of executable. If in precompiled mode, then the library will use INTERFACE type. This is because it has no source files in and out of itself (if you want to keep some source files, then please revert to normal libraries). The library then add include directories, to maintain access to the headers, and links to the precompiled lib.

Then, the top level CMakeLists.txt takes over. It first declare the app’s executable as usual, as well as its source files and dependencies. Then, it includes the library’s CMakeLists.txt, with PRECOMPILED_LIB switch enabled. It can then directly use the precompiled library.

For distribution, simply archive the library folder, after having removed the source files.

Stripping the library

Once you are ready to distribute the code, it is advised to strip the library to obfuscate it. To do so, use the strip command as follows:

riscv32-unknown-elf-strip --strip-debug --strip-unneeded precomp_lib/libprecompiled_lib.a