Linking Libraries Locally with CMake: A Follow-Up

Search for a command to run...

No comments yet. Be the first to comment.
Remember my post about switching to VSCode? Well, plot twist: the very next day after publishing it, I switched to WebStorm. And guess what? I've been on JetBrains IDEs ever since. I know, I know. Another "why I switched editors" post. But hear me ou...

I had been doing some basic interpreter work in Go and wanted to redo it in another language to solidify my understanding. Naturally, I chose Odin, it’s another great language, with a Go-like, easy-to-approach syntax and no unnecessary complexity. I ...

Why Emacs Keybindings? I've always preferred Emacs-style editing, especially the way it handles cursor movement and text manipulation. Even though I have switched to using VSCode for most of my development work, I often found myself missing the intui...

Some time ago, I wrote a post about using Vim to look cool and why that’s not a good idea. Now, funny enough, here I am—having switched to VSCode after years of hopping between Vim and Emacs. This isn’t one of those "Vim sucks, I'm going back to VSCo...

In my previous post about building C/C++ projects with CMake, I shared a simple CMakeLists.txt setup for compiling a basic project. Today, I’ll dive into a specific need that many developers encounter: linking libraries directly from project folders rather than relying on a system-wide installation. Why Link Libraries Locally?
Sometimes, you might want to keep your dependencies within your project directory, whether for portability, version control, or simply to avoid installing extra packages globally. Here’s how I set this up with CMake. Updated CMakeLists.txt Example for Local Libraries
This is the setup I use to link Raylib (a popular C library for game development) directly from my libs folder.
cmake_minimum_required(VERSION 3.29)
project(Game)
# Set the C++ standard version
set(CMAKE_CXX_STANDARD 20)
# Include and link directories for Raylib (in ./libs folder)
include_directories("./libs/raylib-5.0_linux_amd64/include")
link_directories("./libs/raylib-5.0_linux_amd64/lib")
add_executable(Game main.cpp)
# Link dynamically to Raylib
# Comment this if you are going with static linking
target_link_libraries(Game PRIVATE raylib)
# Uncomment the following line if you prefer static linking
# target_link_libraries(cppray PRIVATE raylib.a)
include_directories: Adds headers for Raylib.
link_directories: Adds the path to the Raylib library files.
target_link_libraries: Specifies whether you’re linking dynamically or statically (toggle as needed).
In the first post, I used target_link_libraries(Game raylib) without specifying local paths, assuming a system-wide installation. While that approach is simpler, linking libraries from subdirectories can be more portable, especially for sharing projects or working across different environments.