[c++] CMakeLists代码示例

CMakeLists实例



前言

利用Essential c++ ch2中冒泡排序法作为例,搭建相关的CMakeLists结构。主要涉及,程序结构、静态库的建立、库与目标文件建立联系、各个变量以及关键字的使用与注意事项。


程序框架

    Essential CMakeLists.txt bubble_sort CMakeLists.txt NumricSeq.cpp NumricSeq.h samples CMakeLists.txt ch2 bubble.cpp CMakeLists.txt

代码示例

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 <fstream>
#include <vector>
#include <iostream>
#include "NumericSeq.h"

void swap(int& val1, int& val2, std::ofstream* ofil=0)
{
    if(ofil != 0)
    {
        *ofil << "swap(" << val1
         << "," << val2 << " )
";
    }

    int temp = val1;
    val1 = val2;
    val2 = temp;

    if(ofil != 0)
    {
        *ofil << "after swap(): val1" << val1
             << " val2: " << val2 << "
";
    }
}

void bubble_sort(std::vector<int>& vec, std::ofstream* ofil=0)
{
    for(int ix=0; ix<vec.size(); ix++)
    {
        for(int jx = ix+1; jx<vec.size(); jx++)
        {
            if(vec[ix]>vec[jx])
            {
                // 调试用的输出信息
                if(ofil != 0)
                {
                    (*ofil) << "about to call swap!"
                                        << " ix: " << ix << " jx: " << jx << 	
                                        << " swapping: " << vec[ix]
                                        << " with " << vec[jx] << std::endl;
                }
                swap(vec[ix], vec[jx], ofil);
                display(vec);
            }
        }
    }
}

void display(std::vector<int> vec, std::ostream& os)
{
    for(int ix=0; ix<vec.size(); ix++)
    {
        os << vec[ix] << " ";
    }
    os << std::endl;
}

Essential/bubble_sort/NumricSeq.h

void display(std::vector<int>, std::ostream& = std::cout);
void swap(int&, int&, std::ofstream*);
void bubble_sort(std::vector<int>&, 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 <iostream>
#include <vector>
#include <fstream>
#include "bubble_sort/NumericSeq.h"

int main()
{
    int ia[8] = {8, 34, 3, 13, 1, 21, 5, 2};
    std::vector<int> 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..net/LY_970909/article/details/124833796?spm=1001.2014.3001.5502

经验分享 程序员 微信小程序 职场和发展