mac安装pkg-config并配置homebrew的路径,寻找第三方库的过程概览

brew install pkg-config

配置pkg-config-path

export PKG_CONFIG_PATH=$(find /usr/local/Cellar -name 'pkgconfig' -type d | grep lib/pkgconfig | tr '\n' ':' | sed s/.$//)

test

pkg-config --cflags glib-2.0 
pkg-config --libs --cflags sdl2

寻找第三方库的方法

  • find_package
  • pkg-config
  • git-submodules

假设前提

# 为项目寻找sdl2库,但还没有开始找
 cmake_minimum_required(VERSION 3.10)
 project(findlibs)
add_executable(main src/main.cpp)

开始找包(不建议先使用find_package)

cmake_minimum_required(VERSION 3.10)
project(findlibs)
add_executable(main src/main.cpp)
#1#####################
#find_package(SDL2 REQUIRED)
#target_link_libraries(main PRIVATE SDL2::SDL2)

#2####################
find_package(PkgConfig REQUIRED)
pkg_check_modules(SDL2 sdl2 REQUIRED IMPORTED_TARGET)#SDL2是return name
target_link_libraries(main PRIVATE PkgConfig::SDL2)#find that return name
#加上第二个方法的指令后,能在main.cpp使用SDL库了,但是build了不能运行出来窗口
#3####################
#克隆sdl源码到3rdparty/SDL
add_subdiretory(3rdpart/SDL)
target_link_libraries(main PRIVATE SDL2::SDL2)
#非常坑爹,学习gcc makefile吧,原生导入include和链接库
#4####################
#凡是第三方库,自定义一个cmake文件夹,编写.cmake文件导入第三方库,在主cmakelists.txt加入include(cmake/FindSDL2.cmake)

FindSDL2.cmake

find_path(SDL2_INCLUDE_PATH SDL.h PATHS 3rdlib/SDL/include/SDL2 REQUIRED)#SDL_INCLUDE_DIR是变量名
find_path(SDL2_LIB_PATH libSDL2.a PATHS 3rdlib/SDL2/lib REQUIRED)

message(STATUS "include dir: ${SDL2_INCLUDE_PATH}")

add_library(SDL2::SDL2 INTERFACE IMPORTED)
set_target_properties(
	SDL2::SDL2
	PROPERTIES
		INTERFACE_INCLUDE_DIRECTORIES "${SDL2_INCLUDE_PATH}"
		INTERFACE_LINK_LIBRARIES "-L${SDL2_LIB_PATH} -lmingw32 -lsdl2_main -lSDL2 -mwindows" #mingw for win, window for app type
		IMPORTED_LINK_INTERFACE_LANGUAGES "C" #c lang 
)

还可以参考之前在vscode 配置sdl2环境的教程,在本目录下

你可能感兴趣的:(为c++使用cmake,macos,linux,bash)