Sengeki
Sengeki

Reputation: 65

Linker Error When Linking GLAD with OpenGL and GLFW in CMake/MSBuild

I'm working on an OpenGL project using GLFW and GLAD in a CMake-based setup:

cmake_minimum_required(VERSION 3.16)  # Specify the project name and the languages
project(MyApp LANGUAGES CXX)

# Set C++ standard
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# Include directories
include_directories(MyApp PUBLIC 
    ${CMAKE_SOURCE_DIR}/Libraries/include
    ${CMAKE_SOURCE_DIR}/Resources
    ${CMAKE_SOURCE_DIR}/Shaders
)

# Add executable
add_executable(MyApp  
    main.cpp
    stb.cpp
    folder/File.cpp
)

# Link libraries
target_link_libraries(MyApp PRIVATE 
    opengl32.lib
    ${CMAKE_SOURCE_DIR}/Libraries/lib/glfw3.lib
)

...and I'm encountering a linker error related to GLAD:

LNK2019: unresolved external symbol __imp__gladLoaderLoadGL

I've configured the project to use GLAD with OpenGL, and I'm able to build the GLFW library through Vcpkg successfully.

I've verified that GLAD is installed and properly included in the project. However, the linking still fails. I also tried manually including the glad.c file in the project, but the issue persists.

Why am I getting the unresolved external symbol error and how to properly link GLAD with my OpenGL project?

Upvotes: 1

Views: 81

Answers (1)

Sengeki
Sengeki

Reputation: 65

The issue stemmed from several oversights in the project setup. The language for the project wasn't explicitly defined as C and CXX. This omission caused confusion about the build process and glad was not properly linked as a static library, and its C language specification was missing, leading to compatibility issues.

cmake_minimum_required(VERSION 3.16)

# Specify the project name and languages
project(ShaderToy LANGUAGES C CXX)

# Set C++ standard
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

# Include directories
include_directories(
    ${CMAKE_SOURCE_DIR}/Libraries/include
    ${CMAKE_SOURCE_DIR}/Resources
    ${CMAKE_SOURCE_DIR}/Shaders
)

# Add glad as a library and specify its language
add_library(glad STATIC ${CMAKE_SOURCE_DIR}/glad.c)
set_target_properties(glad PROPERTIES LINKER_LANGUAGE C)

# Add executable
add_executable(ShaderToy 
    main.cpp
    stb.cpp
    Shaders/shaderClass.cpp
)

# Link glad, GLFW, and OpenGL
target_link_libraries(ShaderToy PRIVATE 
    glad
    ${CMAKE_SOURCE_DIR}/Libraries/lib/glfw3.lib 
    opengl32.lib
)

Upvotes: 1

Related Questions