本文给出快速构建C++项目的代码仓库模板 ,简单却完整
主要包括:
-
编译脚本
-
打包上传脚本-
-
依赖拉取
-
代码格式化配置
-
git配置
-
流水线pipeline配置
使用这个模板 你只需要:将源文件放到模块目录下,并添加到cmake中即可
一、简单代码目录组织
├── cicd # 目录:编译打包上传脚本目录
│ ├── build_aarch64_ubuntu.sh # 文件:arm平台编译脚本
│ ├── build_x86_ubuntu.sh # x86平台编译脚本
│ └── upload_pkg.sh # 打包上传脚本(调用编译脚本编译后上传)
├── cmake # 目录:cmake工具
│ └── CPM.cmake # 依赖项拉取工具
├── module # 代码父目录
│ ├── CMakeLists.txt # module的CMake,包含a和b两个子目录
│ ├── sub_module_a # 模块a目录
│ │ ├── CMakeLists.txt # 子模块a的cmake配置
│ │ ├── config # 目录:模块a配置文件目录
│ │ │ ├── aarch64 # 目录:模块 a arm平台配置文件目录
│ │ │ │ └── a.conf
│ │ │ └── x86 # 目录:模块 a x86平台配置文件目录
│ │ │ └── a.conf
│ │ ├── include # 目录:模块a头文件目录
│ │ │ └── a.h
│ │ ├── launch # 目录:模块a启动文件目录
│ │ │ ├── launch_a_aarch64.sh
│ │ │ └── launch_a_x86.sh
│ │ └── src # 目录:模块a源文件目录
│ │ └── main.cpp
│ └── sub_module_b# 目录:模块b目录
├── .clang-format # 代码格式化配置
├── CMakeLists.txt# 项目cmake配置
├── extern_dep.cmake # 项目依赖库配额
├── .gitignore # git忽略配置
├── .gitlab-ci.yml # gitlab ci配置
└── README.md # readme文件
二、文件内容
1. 编译脚本
build_x86_ubuntu.sh
#!/usr/bin/env bash
CURDIR=$(pwd)
SUBDIRNAME="build_x86"
DIRNAME=${CURDIR}/${SUBDIRNAME}
if [ ! -d ${DIRNAME} ]; then
mkdir ${DIRNAME}
else
echo "${DIRNAME} exists"
fi
cd ${DIRNAME} || exit
fullpath=$(pwd)
cmake \
-DCMAKE_INSTALL_PREFIX="${fullpath}/output" \
..
make -j8 && make install
编译说明
# 初始编译
bash cicd/build_x86_ubuntu.sh
# 增量编译
cd build_x86 && make
2. 启动脚本
launch_a_x86.sh
#!/usr/bin/env bash
SCRIPT_PATH="$(
# shellcheck disable=SC2164
cd -- "$(dirname "$0")" >/dev/null 2>&1
pwd -P
)"
PROJ_ROOT="${SCRIPT_PATH}/.."
# shellcheck disable=SC2164
cd "${PROJ_ROOT}"
export LD_LIBRARY_PATH="${PROJ_ROOT}/third_party/lib:${PROJ_ROOT}/lib":${LD_LIBRARY_PATH}
BIN="${PROJ_ROOT}/bin/appname_a"
${BIN}
3. CPM
这个文件的内容较多,这里不展示
可从git查看 https://github.com/cpm-cmake/CPM.cmake
4. 顶层 CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(my_project_name) #Project name
include(cmake/cpm.cmake)
# 添加 module 目录
add_subdirectory(module)
5. 模块 module/CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(module) #Project name
# 添加 module 子目录
add_subdirectory(sub_module_a)
add_subdirectory(sub_module_b)
6. 子模块 module/sub_module_a/CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(module_a) #Project name
add_executable(appname_a main.cc) # 添加可执行文件
7. 依赖拉取 extern_dep.cmake
通过cpm拉取依赖库
include(cmake/CPM.cmake)
# glog
CPMAddPackage(
NAME glog
URL http://10.31.1.173/pkg/glog-0.6.0.tgz
)
include_directories(${glog_SOURCE_DIR}/include)
link_directories(${glog_SOURCE_DIR}/lib)
install(DIRECTORY ${glog_SOURCE_DIR}/lib
DESTINATION third_party
FILES_MATCHING PATTERN "*.so*"
)
# gflags
CPMAddPackage(
NAME gflags
URL http://10.31.1.173/pkg/gflags-2.2.2.tgz
# URL /mnt/nfs/pkg/gflags-2.2.2.tgz
)
include_directories(${gflags_SOURCE_DIR}/include)
link_directories(${gflags_SOURCE_DIR}/lib)
install(DIRECTORY ${gflags_SOURCE_DIR}/lib
DESTINATION third_party
FILES_MATCHING PATTERN "*.so*"
)
# gtest
CPMAddPackage(
NAME gtest
URL http://10.31.1.173/pkg/googletest-1.10.0.tgz
)
include_directories(${gtest_SOURCE_DIR}/include)
link_directories(${gtest_SOURCE_DIR}/lib)
install(DIRECTORY ${gtest_SOURCE_DIR}/lib
DESTINATION third_party
FILES_MATCHING PATTERN "*.so*"
)
8. 代码格式化配置 clang-format
---
Language: Cpp
# BasedOnStyle: Google
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: BeforeColon
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IncludeBlocks: Preserve
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
- Regex: '^<.*\.h>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 2
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
CanonicalDelimiter: ''
BasedOnStyle: google
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Auto
TabWidth: 8
UseTab: Never
9. git忽略配置 gitignore
build*/
output
.idea
.iml
.sln
*.swp
*.local
.DS_Store
*.tmp
.gradle
third_module
build.properties.local
cmake-build-*
*.params
# eclipse
.*project
# windows
windows
win64
# vscode
.vscode/
.idea
vis_result
*kernel_meta*
models
conan.lock
conanbuildinfo.*
conaninfo.*
# data
data/dbc
/install
/log
/tmp
auto-launch/logs/
10. 流水线 gitlab-ci.yml
stages:
- build
- release
- test
# 提交Merge Request触发此流水线
Build::GPU_ubuntu20.04:
stage: build
image: msrd0/cmake-qt5
tags:
- x86_gpu_runner
only:
- merge_requests
script:
- bash cicd/upload_pkg.sh "[this is a merge request]"
# 打tag触发此流水线
Release::GPU_ubuntu20.04:
stage: release
image: msrd0/cmake-qt5
tags:
- x86_gpu_runner
rules:
- if: $CI_COMMIT_TAG
script:
- bash cicd/upload_pkg.sh "[this is a release triggered]"
sast:
stage: test
image: msrd0/cmake-qt5
tags:
- x86_gpu_runner
include:
- template: Security/SAST.gitlab-ci.yml
三、安装目录
├── bin # 目录:二进制可执行文件
│ └── appname_a #可执行文件
├── config # 目录:配置文件目录
│ └── a.conf
├── launch # 目录:启动文件目录
│ └── launch_x86.sh
└── third_party # 目录:依赖库目录
└── lib
├── cmake
├── libglog.so -> libglog.so.1
├── libglog.so.0.6.0
├── libglog.so.1 -> libglog.so.0.6.0
└── pkgconfig