0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CMakeのインストールと使い方

Posted at

インストール

Ubuntuでcmakeをインストールする。

sudo apt update
sudu apt install cmake

最小でビルド

コード

#include <stdio.h>
#include <iostream>

int main() {
    std::cout << "start" << std::endl;
    std::cout << "end" << std::endl;
}

CMakeLists.txtの内容

cmake_minimum_required(VERSION 3.2 FATAL_ERROR)

# set the project name and version
project(sample CXX)

# compile executable file
add_executable(sampleApp sample.cpp)

コンパイルコマンド

mkdir build
cd build
cmake ..
cmake --build .

実行結果

start
end

ヘッダーのパスを省略してビルド

フォルダ構成

.
├── CMakeLists.txt
├── sample.cpp
├── test.txt
└── util
    └── read.h

このとき、utilのパスを省略して実装できるようにCMakeLists.txtにtarget_include_directoriesを追加

cmake_minimum_required(VERSION 3.2 FATAL_ERROR)

# set the project name and version
project(sample CXX)

# compile executable file
add_executable(sampleApp sample.cpp)

# set include directory
target_include_directories(sampleApp PRIVATE ./util)
コード

sample.cpp

#include "read.h"

int main() {
    ReadFile test;
    std::cout << "start" << std::endl;
    test.read("../test.txt");
    std::cout << test.get() << std::endl;
    std::cout << "end" << std::endl;
}

read.h

#pragma once

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>

class ReadFile {
    private:
        std::string data;
    public:
        void read(std::string file_path) {
            std::ifstream ifs(file_path, std::ios::binary); // バイナリモードでファイルを開く
            std::stringstream file_data;
            if (!ifs) {
                std::cerr << "Failed to open file." << std::endl;
                return;
            }

            file_data << ifs.rdbuf(); // ファイルデータを一度に読み込む

            if (file_data.str().empty()) {
                std::cerr << "File size error." << std::endl;
                return;
            }
            data = file_data.str();
            return;
        }
        std::string get() {
            return data;
        }
};

test.txt

hello,world!
good
umauma

実行結果

start
hello,world!
good
umauma
end
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?