FacundoGFlores
FacundoGFlores

Reputation: 8118

Set up cmakelist correctly to compile project

This is my working directory:

app
|___include
  |___file1.h
  |___file2.h
  |___file3.h
  !___ ...
|___src
  |___file1.c
  |___file2.c
  |___file3.c
  |___ ...
|__CMakeLists.txt
|__mainapp.c

And this is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.5.1)
project(app)
include_directories(include)
file(GLOB SOURCES src/*.c)
add_executable(file3 src/file3.c)
target_link_libraries(file3 m ${SOURCES})

Then I do the following:

$cmake .
$make

But I get errors:

[ 50%] Building C object CMakeFiles/file3.dir/src/file3.c.o
[100%] Linking C executable file3
src/file3.c:1:19: fatal error: file1.h: File does not exist

Where file3.c is just:

#include "file1.h"
#include "file2.h"

int foo3(int a, int b){
    return foo1(a,b) + foo2(a,b);
}

How do I set up CMakeLists correctly?

Upvotes: 0

Views: 59

Answers (2)

Christian T
Christian T

Reputation: 56

You are linking source files to your executable but you should compile them.

target_link_libraries(file3 m ${SOURCES})

Normally you put all your source files into the add_executable for compilation and only link libraries like m (libm for math functions).

add_executable(file3 ${SOURCES})
target_link_libraries(file3 m)

This of course only works if none of the other files contain a main function.

Your include_directories(include) is appended to the gcc call as -Iinclude which is used during compilation. https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html. You can see your gcc calls with make VERBOSE=1.

During Linking gcc doesn't look there anymore, that's why it tells you it can't find that function (after that it would probably fail elsewhere)

You could also build a library with your sources and link your executable against that. But then don't include file3 in the sources for the library.

Upvotes: 1

Luanf
Luanf

Reputation: 172

Using

#include "file1.h"

searches for file.h in the current directory and not in the other included directories.

Use

#include <file.h>

instead.

Hope this helps

Upvotes: 0

Related Questions