一个CMake的例子
首先编写4个文件:
1、CMakeLists.txt内容:
cmake_minimum_required(VERSION 3.15) project(Demo) include_directories(${PROJECT_BINARY_DIR}/headers) aux_source_directory(${PROJECT_BINARY_DIR}/sources SRC_DIR) add_library(dynamic_library SHARED ${SRC_DIR}) add_library(static_library STATIC ${SRC_DIR}) set(LIBRARY_OUTPUT_PATH ${PROJECT_BINARY_DIR}/libs) add_executable(demo_dynamic main.cc) target_link_libraries(demo_dynamic dynamic_library) add_executable(demo_static main.cc) target_link_libraries(demo_static static_library) add_compile_options(-std=c++17) set(EXECUTABLE_OUTPUT_PATH ${PROJECT_BINARY_DIR}/bin)
2、sources/foo.cc内容:
#include <functional> #include <iostream> void (*fp1)() = []() {}; void (*fp2)() = []() { std::cout << "In fp2" << std::endl; };
3、headers/bar.h内容:
#include <functional> #include <iostream> void fp3() { std::cout << "In fp3" << std::endl; };
4、main.cc内容:
#include <functional> #include <string> #include <unordered_map> #include "bar.h" extern void (*fp1)(); extern void (*fp2)(); extern void fp3(); void calltable( const std::string &condition, std::unordered_map<std::string, const std::function<void(void)>> &table) { if (table.count(condition)) { table[condition](); } } int main(int argc, char *argv[]) { std::unordered_map<std::string, const std::function<void(void)>> table{ {"1", fp1}, {"2", fp2}, {"3", fp3}, }; std::string condition = "1"; calltable(condition, table); condition = "2"; calltable(condition, table); condition = "3"; calltable(condition, table); }
然后编译、运行:
cmake . && make ./bin/demo_dynamic ./bin/demo_static