CMakeLists.txt and cmake interview questions

What is a cmake?
cmake is a cross platform open source software for managing build system of a software. It generates native makefile which is the recipe file for native make tool to create any application in Linux. It is also used with other native build environments such as make Apple's Xcode, and Microsoft Visual Studio.
It supports directory hierarchies. Each directory contains a CMakeLists.txt file.
It supports applications that depends on multiple libraries.
What is CMakeLists.txt?
CMakeLists.txt file contains instruction to "cmake" tool to generate a native Makefile which the instructions file for "make" to create an application.

A Simple multi folder camke project example say MyProject.Simple cmake demo example can be found here.
MyProject
├── CMakeLists.txt
├── myapp
│   ├── CMakeLists.txt
│   └── main.cpp
└── mylibs
    ├── CMakeLists.txt
    ├── mylib.cpp
    └── mylib.h
 

Top most MyProject/CMakeList.txt
cmake_minimum_required(VERSION 2.8)
add_subdirectory(mylibs)
add_subdirectory(myapp)

myapp/CMakeLists.txt
add_executable(app main.cpp)
target_link_libraries(app mylib)

myapp/main.cpp
#include<iostream>
using namespace std;
#include "../mylibs/mylib.h"
int main()
{
cout<<"main"<<endl;
libfun1();
libfun2();
return 0;
}

mylibs/CMakeLists.txt
add_library(mylib mylib.cpp)

mylib/mylib.cpp
#include<iostream>
using namespace std;
void libfun1()
{
cout<<"libfun1"<<endl;
}
void libfun2()
{
cout<<"libfun2"<<endl;
}

mylib/mylib.h
void libfun1();
void libfun2();

How to build in a separate direcory
cd MyProject
mkdir build
cd build
cmake -DCMAKE_INSTALL_PREFIX:PATH=/tmp/foo
make
make install.
Summary:
    Using CMake with executables
    add_executable(myapp main.c)

    Using CMake with static libraries
    add_library(test STATIC test.c)

    Using CMake with dynamic libraries
    add_library(test SHARED test.c)

    Linking libraries to executables with CMake
    add_subdirectory(libtest_project)
    add_executable(myapp main.c)
    target_link_libraries(myapp test)

No comments:

Post a Comment