The classic hello world

Goal

In this short tutorial we learn how to use CMake. We compile a simple test program that links all YARP libraries and is ready to use all the libraries in the iCub repository. This program is trivial and does not use the robot yet.

We assume you have:

First we need to prepare the main.cpp.

Open a text editor and type the following:

#include <stdio.h>
#include <yarp/os/Time.h>

int main()
{
        printf("Starting the application\n");
        int times=10;

        while(times--)
        {
                printf("Hello iCub\n");
                Time::delay(0.5); //wait 0.5 seconds
        }
        printf("Goodbye!\n");
}

Save it to main.cpp.

This program will print the "Hello iCub" message for some times, waiting 0.5 seconds at every iteration of the while loop.

Let's see now how to compile this program.

Go back to your text editor and write the following file:

PROJECT(HELLO_ICUB)

FIND_PACKAGE(YARP)
FIND_PACKAGE(ICUB)

# add include directories
INCLUDE_DIRECTORIES(${YARP_INCLUDE_DIRS} ${ICUB_INCLUDE_DIRS})

# add required linker flags
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${ICUB_LINK_FLAGS}")              

ADD_EXECUTABLE(hello main.cpp)

# we now add the YARP and iCub libraries to our project.
TARGET_LINK_LIBRARIES(hello ${YARP_LIBRARIES} ${ICUB_LIBRARIES})

Now save this file as CMakeLists.txt, in the same directory as your main.cpp file.

This code tells cmake to produce appropriate project files to compile an executable named hello, using the file main.cpp. It also links in yarp libraries and sets up your environment to link other libraries from the iCub repository.

Now run cmake:

cmake ./

If cmake complains about not being able to localize YARP or ICUB, it means that you have not followed correctly the procedure in the manual about the compilation of YARP or the installation of the iCub repository. In particular check that you have correctly set the environment veriables ICUB_ROOT/ICUB_DIR and YARP_ROOT/YARP_DIR. It is also possible to manually set these values, but we do not recommend it.

Now you are ready to compile this example using your favorite compiler, and execute it.

In linux:

make
./hello
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Friends Defines