目录结构
文件内容
#ifndef MYSHAREDLIB_HELLO_H
#define MYSHAREDLIB_HELLO_H
// 打印 Hello World!
void hello();
// 使用可变模版参数求和
template <typename T>
T sum(T t)
{
return t;
}
template <typename T, typename ...Types>
T sum(T first, Types ... rest)
{
return first + sum<T>(rest...);
}
#endif
#include <iostream>
#include "Hello.h"
void hello() {
std::cout << "Hello, World!" << std::endl;
}
#include <iostream>
#include "Hello.h"
using std::cout;
using std::endl;
int main() {
hello();
cout << "1 + 2 = " << sum(1,2) << endl;
cout << "1 + 2 + 3 = " << sum(1,2,3) << endl;
return 0;
}
cmake基本脚本
#cmake版本
cmake_minimum_required(VERSION 3.5)
# 项目名称
project(hello_library)
# 根据库文件代码生成静态库
add_library(hello_library STATIC src/Hello.cpp)
# 包含指定头文件所在的目录
target_include_directories(hello_library PUBLIC ${PROJECT_SOURCE_DIR}/include/static)
# 创建可执行程序
add_executable(hello_binary src/main.cpp)
# 链接静态库文件
target_link_libraries( hello_binary PRIVATE hello_library)
编译
mkdir build
cd build
cmake ..
make
./hell_binary
返回结果
Hello, World!
1 + 2 = 3
1 + 2 + 3 = 6