利用Essential c++ ch2中冒泡排序法作为例,搭建相关的CMakeLists结构。主要涉及,程序结构、静态库的建立、库与目标文件建立联系、各个变量以及关键字的使用与注意事项。
Essential/CMakeLists.txt
cmake_minimum_required(VERSION 3.22.0)
project(InvokeFunction)
add_subdirectory(bubble_sort)
add_subdirectory(samples)
Essential/bubble_sort/CMakeLists.txt
project(bubble_sort)
set(HEADERS
${CMAKE_CURRENT_SOURCE_DIR}/NumericSeq.h
)
set(SOURCE
${CMAKE_CURRENT_SOURCE_DIR}/NumericSeq.cpp
)
add_library(bubble_sort ${HEADERS} ${SOURCE})
Essenetial/bubble/NumricSeq.cpp
#include
#include
#include
#include "NumericSeq.h"
void swap(int& val1, int& val2, std::ofstream* ofil=0)
{
if(ofil != 0)
{
*ofil << "swap(" << val1
<< "," << val2 << " )\n";
}
int temp = val1;
val1 = val2;
val2 = temp;
if(ofil != 0)
{
*ofil << "after swap(): val1" << val1
<< " val2: " << val2 << "\n";
}
}
void bubble_sort(std::vector& vec, std::ofstream* ofil=0)
{
for(int ix=0; ixvec[jx])
{
// 调试用的输出信息
if(ofil != 0)
{
(*ofil) << "about to call swap!"
<< " ix: " << ix << " jx: " << jx << '\t'
<< " swapping: " << vec[ix]
<< " with " << vec[jx] << std::endl;
}
swap(vec[ix], vec[jx], ofil);
display(vec);
}
}
}
}
void display(std::vector vec, std::ostream& os)
{
for(int ix=0; ix
Essential/bubble_sort/NumricSeq.h
void display(std::vector, std::ostream& = std::cout);
void swap(int&, int&, std::ofstream*);
void bubble_sort(std::vector&, std::ofstream*);
Essential/samples/CMakeLists.txt
add_subdirectory(ch2)
Esstial/samples/ch2/CMakeLists.txt
project(ch2)
include_directories("../..")
set(BUBBLE
bubble.cpp
)
add_executable(bubble ${BUBBLE})
target_link_libraries(bubble bubble_sort)
Essential/samples/ch2/bubble.cpp
#include
#include
#include
#include "bubble_sort/NumericSeq.h"
int main()
{
int ia[8] = {8, 34, 3, 13, 1, 21, 5, 2};
std::vector vec(ia, ia+8); // 利用数组初始化vector的方法
std::ofstream ofil("text_out1");
std::cout << "vector before sort: ";
display(vec);
bubble_sort(vec, &ofil);
std::cout << "vector after sort: ";
display(vec);
}
相关命令含义请参考:https://blog.csdn.net/LY_970909/article/details/124833796?spm=1001.2014.3001.5502