# Creating a library ¶

This tutorial only covers 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

## Requirements ¶

We assume you have a qiBuild project containing a executable named  foo  .

You can use  qisrc 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



///
/// Get the meaning of life
///




{
return 42;
}



Then, edit main.cpp to have:



#include <stdio>

int main()
{
return 0;
}



## Using the answer library ¶

In order to use our library in the foo executable, we have to:

• Find the  answer.h  file : so we need to add some include directories
• Create a library named answer with  answer.h  and  answer.cpp 
• Link the  foo  executable with the  answer  library.

### Adding the include directories ¶

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

### Creating the answer library ¶





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.

## Building ¶

You can then build your project.

A few notes:

• On Windows, the library will be found in  build/sdk/lib/answer_d.lib  if built in debug, or in  build/sdk/lib/answer.lib  if built in release.
• On linux, the library will be found in  build/sdk/lib/libanswer.so 
• On mac, the library will be found in  build/sdk/lib/libanswer.dylib 

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.

## Conclusion ¶

The final CMakeLists.txt code looks like



cmake_minimum_required(VERSION 2.8)
find_package(qibuild)
project(foo)

include_directories(".")