-1

I'm trying to link GLFW using git submodule. Here is my CMakeLists.txt:

cmake_minimum_required(VERSION 3.0.0)
project(guitest VERSION 0.1.0 LANGUAGES C CXX)

add_executable(guitest main.cpp)

add_subdirectory(glfw)
include_directories(glfw/include)
link_directories(glfw/src)
link_libraries(glfw)

I get no errors in CMake, but when I try to build my project I get

[build] C:/Users/Konstantin/Documents/sasha/guitest/main.cpp:7: undefined reference to `glfwInit'

Here is my code

#include <iostream>
#include <GLFW/glfw3.h>


int main(int, char**){
    GLFWwindow *window;
    if(!glfwInit()){
        std::cout << "Init failure!"<<std::endl;
        exit(EXIT_FAILURE);
    }
}

I'm using Visual Studio Code and GCC 6.3.0 MinGW compiler kit.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
moonlags
  • 13
  • 1
  • Please create a verbose makefile, and take a look at the commands being executed to see all the flags and options. – Some programmer dude Jun 08 '23 at 10:48
  • Also note that `include_directories`, `link_directories` and `link_libraries` are all discouraged, in favor of [`target_include_directories`](https://cmake.org/cmake/help/latest/command/target_include_directories.html#command:target_include_directories) and [`target_link_libraries`](https://cmake.org/cmake/help/latest/command/target_link_libraries.html). – Some programmer dude Jun 08 '23 at 10:50

1 Answers1

3

The command link_libraries affects only on targets which are created after. Since your call to add_executable precedes link_libraries, your executable is not linked.

Correct (but not the best):

add_subdirectory(glfw)
link_libraries(glfw)
add_executable(guitest main.cpp)

It is preferred to use target_link_libraries instead of link_libraries.

add_subdirectory(glfw)
add_executable(guitest main.cpp)
target_link_libraries(guitest PRIVATE glfw)

In both cases include_directories call could be omitted, since linkage with glfw target also ships your executable with GLFW include directories.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153