This tutorial only convers the most simple way of writing a library.
If you are working in a large project, or wish to re-distribute your library, you may want to read this more in-depth tutorial: How to write a library
We assume you have a qiBuild project containing a executable named foo.
You can use qibuild create foo to get such a project.
We are going to write a function called get_answer() that will return an integer.
Since this function may be used by other people, we are going to put it in a library, called answer
Add the following files into your project:
// answer.h
///
/// Get the meaning of life
///
int get_answer();
// answer.cpp
#include "answer.h"
int get_answer()
{
return 42;
}
Then, edit main.cpp to have:
#include <stdio>
#include "answer.h"
int main()
{
std::cout << "The answer is: " << get_answer() << std::endl;
return 0;
}
In order to use our library in the foo executable, we have to:
Add the following line to the CMakeLists.txt:
include_directories(".")
Note
CMake always interprets paths relative to the current CMakeLists file So since the CMakeLists and your headers are in the same directory, include_directories(”.”) is enough
Add a call to qi_create_lib:
qi_create_lib(answer answer.h answer.cpp)
This creates a static library by default, named libanswer.a on UNIX, and answer.lib or answer_d.lib on Windows.
It also makes the answer library usable by other targets.
Add a call to qi_use_lib:
qi_use_lib(foo answer)
Make sure you call this after the call to qi_create_lib - you need to create a library before using it.
This call does several things:
You can then build your project.
A few notes:
Note
On UNIX, you can force the creation of static library by using -DBUILD_SHARED_LIBS=OFF
On Windows, the sources need to be patched to use answer as a shared library, but this out of the scope of this documentation.
The final CMakeLists.txt code looks like
cmake_minimum_required(VERSION 2.6.4)
include(qibuild.cmake)
project(foo)
include_directories(".")
qi_create_lib(answer answer.h answer.cpp)
qi_create_bin(foo main.cpp)
qi_use_lib(foo answer)