CMake Cookbook
上QQ阅读APP看书,第一时间看更新

Getting ready

Let us go back to our very first example. However, instead of having one single source file for the executable, we will now introduce a class to wrap the message to be printed out to screen. This is our updated hello-world.cpp:

#include "Message.hpp"

#include <cstdlib>
#include <iostream>

int main() {
Message say_hello("Hello, CMake World!");

std::cout << say_hello << std::endl;

Message say_goodbye("Goodbye, CMake World");

std::cout << say_goodbye << std::endl;

return EXIT_SUCCESS;
}

The Message class wraps a string, provides an overload for the << operator, and consists of two source files: the Message.hpp header file and the corresponding Message.cpp source file. The Message.hpp interface file contains the following:

#pragma once

#include <iosfwd>
#include <string>

class Message {
public:
Message(const std::string &m) : message_(m) {}

friend std::ostream &operator<<(std::ostream &os, Message &obj) {
return obj.printObject(os);
}

private:
std::string message_;
std::ostream &printObject(std::ostream &os);
};

The corresponding implementation is contained in Message.cpp:

#include "Message.hpp"

#include <iostream>
#include <string>

std::ostream &Message::printObject(std::ostream &os) {
os << "This is my very nice message: " << std::endl;
os << message_;

return os;
}