简体   繁体   English

如何使用 Ninja 在 C++ 中编译“Hello World”?

[英]How to compile “Hello World” in C++ with Ninja?

I'm new with Ninja.我是忍者的新手。 Still don't know how to use it.还是不知道怎么用。

I created a simple hello.cpp file:我创建了一个简单的hello.cpp文件:

#include <iostream>
int main()
{
        std::cout << "Hello World!" << std::endl;
        return 0;
}

I am using Linux Ubuntu.我正在使用 Linux Ubuntu。

I have installed CMake with: apt install cmake我已经安装了 CMake: apt install cmake

and I have installed ninja: apt-get install ninja-build我已经安装了忍者: apt-get install ninja-build

But now what should I do to compile my hello.cpp file with Ninja?但是现在我应该怎么做才能用 Ninja 编译我的hello.cpp文件呢?

I tried to run ninja but I'm getting error about rules.ninja :我试图运行ninja ,但我收到有关rules.ninja的错误:

ninja: error: build.ninja:30: loading 'rules.ninja': No such file or directory

I don't know how to create rules.ninja and how to configure it, and I don't know if I miss more things.我不知道如何创建rules.ninja以及如何配置它,也不知道我是否错过了更多的东西。

Assuming here that you do not have a CMakeLists.txt file at all.假设您根本没有CMakeLists.txt文件。 To compile this program, you first need to create a CMakeLists.txt file.要编译这个程序,首先需要创建一个CMakeLists.txt文件。 This file is used by CMake to configure the project. CMake 使用此文件配置项目。

CMakeLists.txt (place it in the same folder as your source files): CMakeLists.txt (将其放在与源文件相同的文件夹中):

cmake_minimum_required(VERSION 3.8)
project(my_exe)
set(CMAKE_CXX_STANDARD 14) # Try 11 if your compiler does not support C++14
add_executable(my_exe hello.cpp)

Then you need to invoke CMake (in the terminal, go to the folder containing the CMakeLists.txt file) and later build the project.然后你需要调用 CMake (在终端中, go 到包含CMakeLists.txt文件的文件夹),然后构建项目。

First, you should create a build directory.首先,您应该创建一个构建目录。 This is handy since you don't want to mix build output with your project files.这很方便,因为您不想将构建 output 与您的项目文件混合。

mkdir build
cd build

Then, you invoke CMake and tell it to generate a Ninja build system ( -GNinja ), while at the same time tell it where the CMakeLists.txt file is located ( .. ), which should be directly below the build folder:然后,您调用 CMake 并告诉它生成一个 Ninja 构建系统( -GNinja ),同时告诉它CMakeLists.txt文件的位置( .. ),它应该在build文件夹的正下方:

cmake -GNinja ..

Now, you are ready to build the executable:现在,您已准备好构建可执行文件:

ninja

Done.完毕。 You should now have an executable name my_exe in your build folder.现在,您的build文件夹中应该有一个可执行文件名my_exe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM