User Tools

Site Tools


projtec:cmake

This is an old revision of the document!


CMake

Hello World

Considérons le petit exemple suivant :

hello.c
#include <stdio.h>
 
int main() {
  printf("Hello World!\n");
  return 0;
}

Voici un fichier CMakeLists.txt minimaliste pour compiler ce petit projet :

CMakeLists.txt
cmake_minimum_required(VERSION 2.6)
project(HelloWorld)
add_executable(hello hello.c)

Pour générer un Makefile et compiler notre projet, il faut taper les commandes suivantes :

cmake .
make        # ou make VERBOSE=ON

Un peu plus compliqué

Considérons maintenant dans notre projet plusieurs fichiers sources (hello.c, pouet.c, pouet.h) et une bibliothèque extérieure (la library m associé à <math.h> qui contient la définition de la fonction sqrt()).

hello.c
#include <stdio.h>
#include "pouet.h"
 
int main() {
  printf("Hello World!\n");
  pouet();
  return 0;
}
pouet.h
void pouet();
pouet.c
#include <stdio.h>
#include <math.h>
 
void pouet() {
  printf("sqrt(2) = %.6f\n", sqrt(2)); 
}

Voici donc le fichier CMakeLists.txt pour compiler tout cela. On a également ajouté des variables CMAKE par défaut : CMAKE_C_FLAGS et CMAKE_INSTALL_PREFIX pour le répertoire d'installation…

CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (HelloWorld C)
set(CMAKE_C_FLAGS "-std=c99 -g -Wall")
set(CMAKE_INSTALL_PREFIX "install")
add_executable(hello hello.c pouet.c)
target_link_libraries(hello m)
install(TARGETS hello RUNTIME DESTINATION bin)

Ensuite, on fait…

cmake .
make
make install

Utilisation d'une bibliothèque interne

Considérons maintenant le projet suivant :

├── CMakeLists.txt
├── hello.c
├── mylib
│   ├── CMakeLists.txt
│   ├── mylib.c
│   └── mylib.h
├── pouet.c
└── pouet.h

(…)

hello.c
 

#include <stdio.h> #include “pouet.h” #include “mylib.h”

int main() {

printf("Hello World!\n");
pouet();
mylib_foo();
mylib_bar();
return 0;

}

</code>

Voici donc le fichier CMakeLists.txt pour compiler tout cela. On a également ajouté des variables CMAKE par défaut : CMAKE_C_FLAGS et CMAKE_INSTALL_PREFIX pour le répertoire d'installation…

CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
project (HelloWorld C)
set(CMAKE_C_FLAGS "-std=c99 -g -Wall")
set(CMAKE_INSTALL_PREFIX "install")
add_executable(hello hello.c pouet.c)
target_link_libraries(hello m)
install(TARGETS hello RUNTIME DESTINATION bin)

Ensuite, on fait…

cmake .
make
make install

Biblio

projtec/cmake.1485369121.txt.gz · Last modified: 2024/03/18 15:05 (external edit)