Ubuntuの(18.04)C / C ++の概要道をコンパイルして実行 - ネットワーク全体が比較的完全な要約ペーストシリーズです(A)

簡単な紹介

私たちは現在、Unixのシリーズ(CentOSに、Ubuntu.etc)プラットフォームは、より多くの、どのようにコンパイルし、C / C ++は、一連のプラットフォームへの最初のステップとなっています実行するために使用していると信じて、最近いくつかの方法をコンパイルし、現在の主流をまとめるために時間を割いて。結論として、それはに分けることができますCMakeLists、メイクファイル、g ++および一部などEclipseやQtcreatorとしてIDEを使用しては、Ubuntuの下、現在、比較的一般的なプラットフォームです。もちろんVScodeは、CLion、Pycharmは、することができますが、前者は分類コードやソフトウェア、CMakeListsによるものであるか、コンパイルまたはその他の使用、以下の4種類がコンパイルして導入された実行モード、CMakeLists、メイクファイル、G ++、QtcreatorとコンパイルEclipseが。

方法1:CMakeListsの道(公式サイトドライブを教えてくれました)ここで公式サイトに行く7つのステップがあり、人生の頂点へのステップバイステップ

ステップ1:入力CMakeLists

最初のステップに入る:再生を始めます

最も簡単な方法へのわずか2行、1行の記述プロジェクト名、以下の手順の件名:

1、最初ちょうどここのチュートリアルを名前を選択し、フォルダを作成
$ mkdir Tutorial
図2に示すように、タッチ、geditの又はVIM / VI CMakeLists.txt、 そして次の2行を書き込みます。注意: CMakeLists.txtの場合は関係ありません。
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
add_executable(Tutorial tutorial.cpp)

または:あなたは、イニシアチブは、ソースファイルを実行するディレクトリを追加するには、以下のバージョンを使用することができます。

#注意大小写都可以,Cmake不分大小写
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
AUX_SOURCE_DIRECTORY(. DIR_SRCS)
add_executable(Tutorial ${DIR_SRCS})

注意:add_executableが内側にコンパイルすることができますプロジェクトにゴールを追加します。

add_executable(<name> [WIN32] [MACOSX_BUNDLE]
               [EXCLUDE_FROM_ALL]
               source1 [source2 ...])
name: 工程所要构建的目标名称
WIN32/Win64等: 目标app运行的平台
source1:构建目标App的源文件 
図3は、使用のCPPファイルを二乗達成するために、ここでは公式の単純な例ですが、CMakeLists.txtのCXXファイルを追加するためのフォルダを作成します。
1,vim tutorial.cpp 写入如下代码
// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
  double inputValue = atof(argv[1]);
  double outputValue = sqrt(inputValue);
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}
4、次のコンパイルに応じて実行します。

同じディレクトリに最善とCMakeLists.txtを構築注意してください、cmakeのは、このディレクトリレベルでソースファイルをコンパイルするために必要とされます。そうでない場合はお馴染みと親ディレクトリの代わりに次のコードは...、集中的にUNIXファイル構造と、共通のシェルコマンドを学ぶことができます。

$ mkdir build
$ cmake ..
$ make
$./Tutorial

バージョン番号とヘッダーファイルを追加:第二段階に入ります

1、CMakeLists.txtは、バージョン番号を追加、変更
cmake_minimum_required (VERSION 2.6)
project (Tutorial)
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
 
# configure a header file to pass some of the CMake settings
# to the source code
configure_file (
  "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
  "${PROJECT_BINARY_DIR}/TutorialConfig.h"
  )
 
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
include_directories("${PROJECT_BINARY_DIR}")
 
# add the executable
add_executable(Tutorial tutorial.cpp)

注意:次のようにconfigure_fileは別のディレクトリにファイルをコピーし、ファイルの内容を変更し、パラメータの関数が定義されています。

configure_file(<input> <output>
               [COPYONLY] [ESCAPE_QUOTES] [@ONLY]
               [NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
               
cmake会自动定义两个变量
${PROJECT_SOURCE_DIR}:  当前工程最上层的目录
${PROJECT_BINARY_DIR}: 当前工程的构建目录(文中即为build目录)

図2は、本明細書の実施例に使用されるソースファイルいるので、次のとおりです、次TutorialConfig.h、マニュアルを作成し、ノートディレクトリと同じレベルCMakeLists.txtに入れて、後からディレクトリツリーを実行します。
// the configured options and settings for Tutorial
#define Tutorial_VERSION_MAJOR @Tutorial_VERSION_MAJOR@
#define Tutorial_VERSION_MINOR @Tutorial_VERSION_MINOR@
バージョン番号の使用に3は、ネットワークの職員の例によれば、以下のようにコードを修正し、我々は出力を独自のコードを作成することがあります。
// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
 
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"%s Version %d.%d\n",
            argv[0],
            Tutorial_VERSION_MAJOR,
            Tutorial_VERSION_MINOR);
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
  double inputValue = atof(argv[1]);
  double outputValue = sqrt(inputValue);
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}
基本的には図4に示すように、最後のステップは、すべて同じ
$ mkdir build
$ cmake ..
$ make
$./Tutorial
显示如下即可:
./Tutorial Version 1.0
Usage: ./Tutorial number

ステップ2:CMakeListsにライブラリを追加します。

1.今、我々はCMakeListsにライブラリを追加します。機能を置き換えるためにコンパイラで、乗の機能を追加するために、公式ウェブサイトを参照します。ここではサブフォルダのMathFunctions、CMakeLists.txtにこのLIBを入れて、以下のように、ディレクトリに新しいファイルを作成して追加します。

 aux_source_directory(. DIR_MATH_SRCS)
add_library(MathFunctions ${DIR_MATH_SRCS})

次のようにソースコードは次のとおりです。

#include "MathFunctions.h"
#include <stdio.h>

// a hack square root calculation using simple operations
double mysqrt(double x)
{
  if (x <= 0) {
    return 0;
  }

  double result;
  double delta;
  result = x;

  // do ten iterations
  int i;
  for (i = 0; i < 10; ++i) {
    if (result <= 0) {
      result = 0.1;
    }
    delta = x - (result * result);
    result = result + 0.5 * delta / result;
    fprintf(stdout, "Computing sqrt of %g to be %g\n", x, result);
  }
  return result;
}

ヘッダファイル、ヘッダファイル(MathFunctions.h)次のように読み込みも必要です。

double mysqrt(double x);

次のように現在のディレクトリ構造は以下のとおりです。

├── CMakeLists.txt
├── MathFunctions
│   ├── CMakeLists.txt
│   ├── MathFunctions.h
│   └── mysqrt.cpp
├── TutorialConfig.h.in
└── tutorial.cpp

今度は、最上位のCMakeLists.txtを変えてみましょう

  1. 新しく追加されたライブラリがプロジェクトでコンパイルされていることを確認(MathFunctions)add_subdirectoryを追加
  2. 新しいヘッダファイルのパスを追加しますMathFunctions / MathFunctions.h
  3. 実行可能ファイルに新しいライブラリを追加
    CMakeLists.txtを次のように新しく追加されました
include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
add_subdirectory (MathFunctions) 
 
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial MathFunctions)

最終更新tutorial.cpp次のように:

// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
#include "MathFunctions.h" 
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"%s Version %d.%d\n",
            argv[0],
            Tutorial_VERSION_MAJOR,
            Tutorial_VERSION_MINOR);
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
  double inputValue = atof(argv[1]);
  double outputValue = mysqrt(inputValue);
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}

図2に示すように、次はの形で作られたライブラリーを選択することができます

まず、我々はオプションオプションCMakeLists.txtの最上位を追加します

# should we use our own math functions?
option (USE_MYMATH 
        "Use tutorial provided math implementation" ON) 

あなたは、ユーザーが必要に応じて選択することができますcmakeのを実行するとGUIが表示されます。次の変更は、コンパイルとリンクライブラリかどうかMathFuntionsを追加することです。
次のようにCMakeLists.txtが変更されました。

# add the MathFunctions library?
#
if (USE_MYMATH)
  include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
  add_subdirectory (MathFunctions)
  set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
 
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial  ${EXTRA_LIBS})

メインは、複数のライブラリを容易にしたときになるように前記可変のバックEXTRA_LIBSライブラリは、収集するために使用することができます。
このとき、新しいコードtutorial.cppは、主な違いマクロ定義を使用して、次のように更新日:

// A simple program that computes the square root of a number
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "TutorialConfig.h"
#ifdef USE_MYMATH
#include "MathFunctions.h"
#endif
 
int main (int argc, char *argv[])
{
  if (argc < 2)
    {
    fprintf(stdout,"%s Version %d.%d\n", argv[0],
            Tutorial_VERSION_MAJOR,
            Tutorial_VERSION_MINOR);
    fprintf(stdout,"Usage: %s number\n",argv[0]);
    return 1;
    }
 
  double inputValue = atof(argv[1]);
 
#ifdef USE_MYMATH
  double outputValue = mysqrt(inputValue);
#else
  double outputValue = sqrt(inputValue);
#endif
 
  fprintf(stdout,"The square root of %g is %g\n",
          inputValue, outputValue);
  return 0;
}

ソースコードを直接使用することができますではUSE_MYMATH私達はちょうどTutorialConfig.h.inに以下を追加する必要があります。

#cmakedefine USE_MYMATH

結果は以下の通りであります:

$ ./Tutorial 22
Computing sqrt of 22 to be 11.5
Computing sqrt of 22 to be 6.70652
Computing sqrt of 22 to be 4.99346
Computing sqrt of 22 to be 4.69961
Computing sqrt of 22 to be 4.69042
Computing sqrt of 22 to be 4.69042
Computing sqrt of 22 to be 4.69042
Computing sqrt of 22 to be 4.69042
Computing sqrt of 22 to be 4.69042
Computing sqrt of 22 to be 4.69042
The square root of 22 is 4.69042

ステップ3:CMakeListsへの追加インストールとテスト

1は、その後、私たちは私たちのプロジェクトにルールやテストのサポートをインストールするに参加します。直接インストール我々が設定することができますルールに従うために、ここでは例としてMathFunctionsを継続して使用します。CMakeLists.txt年のMathFunctionsに以下を追加します。

install (TARGETS MathFunctions DESTINATION bin)
install (FILES MathFunctions.h DESTINATION include)

私たちはあなたの一番上のCMakeLists.txtに次の2行を取る必要があるアプリケーションの場合

# add the install targets
install (TARGETS Tutorial DESTINATION bin)
install (FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"        
         DESTINATION include)

このステップは、それがコンパイルされてインストールするために、リンクされるように構成して準備ができてインストールし、システムが自動的に対応するヘッダファイル、ライブラリ、および実行可能ファイルをインストールします。ルートディレクトリにインストールする必要があるファイルを指定するために使用されてcmakeの変数CMAKE_INSTALL_PREFIX。
以下のように、単にアプリケーションが正常に動作していることを確認するためにCMakeList.txtファイルの先頭に基本的な一連のテストを追加し、テストケースを追加します。

include(CTest)

# does the application run
add_test (TutorialRuns Tutorial 25)
# does it sqrt of 25
add_test (TutorialComp25 Tutorial 25)
set_tests_properties (TutorialComp25 PROPERTIES PASS_REGULAR_EXPRESSION "25 is 5")
# does it handle negative numbers
add_test (TutorialNegative Tutorial -25)
set_tests_properties (TutorialNegative PROPERTIES PASS_REGULAR_EXPRESSION "-25 is 0")
# does it handle small numbers
add_test (TutorialSmall Tutorial 0.0001)
set_tests_properties (TutorialSmall PROPERTIES PASS_REGULAR_EXPRESSION "0.0001 is 0.01")
# does the usage message work?
add_test (TutorialUsage Tutorial)
set_tests_properties (TutorialUsage PROPERTIES PASS_REGULAR_EXPRESSION "Usage:.*number")

あなたは多くのテストを使用する必要がある場合は、テスト用にコンパイルCTESTの完了後に使用することができ、それはコードを合理化するために、以下のマクロ定義を使用するのが最適です。

#define a macro to simplify adding tests, then use it
macro (do_test arg result)
  add_test (TutorialComp${arg} Tutorial ${arg})
  set_tests_properties (TutorialComp${arg}
    PROPERTIES PASS_REGULAR_EXPRESSION ${result})
endmacro (do_test)
 
# do a bunch of result based tests
do_test (25 "25 is 5")
do_test (-25 "-25 is 0")

STEP4:相関検出システムはCMakeListsに(イントロスペクションと一つ)を添加し

1は、このステップは、主にそのような例の公式サイトなどの特定の依存性を検出するために使用されて、いないすべてのプラットフォームは、事前に検出する必要があるログやEXP機能を持っていることを前提とし、planBは、コードに置き換えられます。まずCheckFunctionExists.cmakeは、これらの機能は、CMakeListファイルの先頭に以下を追加するかどうかをテストします。

# does this system provide the log and exp functions?
include (CheckFunctionExists)
check_function_exists (log HAVE_LOG)
check_function_exists (exp HAVE_EXP)

2、我々は次の2つのコード行を追加しますTutorialConfig.h変更します。

// does the platform provide exp and log functions?
#cmakedefine HAVE_LOG
#cmakedefine HAVE_EXP

3.最後に、テストはそれは、ログを使用することによって検出された場合、我々はmysqrtを変更、構成TutorialConfig.h、前に完了する必要があることに注意してください。

// if we have both log and exp then use them
#if defined (HAVE_LOG) && defined (HAVE_EXP)
  result = exp(log(x)*0.5);
#else // otherwise use an iterative approach
  . . .

ステップ5:ファイルを追加し、CMakeListsに発電機を生成

このセクションでは、1。我々は計算されたルートは、コードのコンパイルプロセスに追加され、事前にデモを分割コンパイル処理を、生成するソースファイルを追加する方法を学びます。次のようにここでは、このテーブルを生成するために使用される新しいコードを、必要とする、位置コードは、このフォルダMathFunctionsに配置され、(MakeTable.cpp)のコードは次のとおりです。

// A simple program that builds a sqrt table 
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
int main (int argc, char *argv[])
{
  int i;
  double result;
 
  // make sure we have enough arguments
  if (argc < 2)
    {
    return 1;
    }
  
  // open the output file
  FILE *fout = fopen(argv[1],"w");
  if (!fout)
    {
    return 1;
    }
  
  // create a source file with a table of square roots
  fprintf(fout,"double sqrtTable[] = {\n");
  for (i = 0; i < 10; ++i)
    {
    result = sqrt(static_cast<double>(i));
    fprintf(fout,"%g,\n",result);
    }
 
  // close the table with a zero
  fprintf(fout,"0};\n");
  fclose(fout);
  return 0;
}

注意:これは、ジョブの変数アプリケーションとして正しいファイル名を渡す必要があります。

プログラムが正しく実行されるように2、次のステップは、MathFunctionsディレクトリの下に次のコードCMakeLists.txtを追加します。

# first we add the executable that generates the table
add_executable(MakeTable MakeTable.cxx)
 
# add the command to generate the source code
add_custom_command (
  OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/Table.h
  COMMAND MakeTable ${CMAKE_CURRENT_BINARY_DIR}/Table.h
  DEPENDS MakeTable
  )
 
# add the binary tree directory to the search path for 
# include files
include_directories( ${CMAKE_CURRENT_BINARY_DIR} )
 
# add the main library
add_library(MathFunctions mysqrt.cxx ${CMAKE_CURRENT_BINARY_DIR}/Table.h  )

説明:

  1. 実行可能MakeTableを追加
  2. この表を生成するためのユーザコマンドを追加します
  3. Table.hはCMakeのを知っていた環境に追加します
  4. 最後にmysqrt.cppをコンパイルし、このライブラリTable.hに依存する必要があります

:次のように3、最後にトップレベルの変更CMakeLists.txt

cmake_minimum_required (VERSION 2.6)
project (Tutorial)
include(CTest)
 
# The version number.
set (Tutorial_VERSION_MAJOR 1)
set (Tutorial_VERSION_MINOR 0)
 
# does this system provide the log and exp functions?
include (${CMAKE_ROOT}/Modules/CheckFunctionExists.cmake)
 
check_function_exists (log HAVE_LOG)
check_function_exists (exp HAVE_EXP)
 
# should we use our own math functions
option(USE_MYMATH 
  "Use tutorial provided math implementation" ON)
 
# configure a header file to pass some of the CMake settings
# to the source code
configure_file (
  "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in"
  "${PROJECT_BINARY_DIR}/TutorialConfig.h"
  )
 
# add the binary tree to the search path for include files
# so that we will find TutorialConfig.h
include_directories ("${PROJECT_BINARY_DIR}")
 
# add the MathFunctions library?
if (USE_MYMATH)
  include_directories ("${PROJECT_SOURCE_DIR}/MathFunctions")
  add_subdirectory (MathFunctions)
  set (EXTRA_LIBS ${EXTRA_LIBS} MathFunctions)
endif (USE_MYMATH)
 
# add the executable
add_executable (Tutorial tutorial.cxx)
target_link_libraries (Tutorial  ${EXTRA_LIBS})
 
# add the install targets
install (TARGETS Tutorial DESTINATION bin)
install (FILES "${PROJECT_BINARY_DIR}/TutorialConfig.h"        
         DESTINATION include)
 
# does the application run
add_test (TutorialRuns Tutorial 25)
 
# does the usage message work?
add_test (TutorialUsage Tutorial)
set_tests_properties (TutorialUsage
  PROPERTIES 
  PASS_REGULAR_EXPRESSION "Usage:.*number"
  )
 
 
#define a macro to simplify adding tests
macro (do_test arg result)
  add_test (TutorialComp${arg} Tutorial ${arg})
  set_tests_properties (TutorialComp${arg}
    PROPERTIES PASS_REGULAR_EXPRESSION ${result}
    )
endmacro (do_test)
 
# do a bunch of result based tests
do_test (4 "4 is 2")
do_test (9 "9 is 3")
do_test (5 "5 is 2.236")
do_test (7 "7 is 2.645")
do_test (25 "25 is 5")
do_test (-25 "-25 is 0")
do_test (0.0001 "0.0001 is 0.01")

STEP6:CMakeListsを追加するために建設インストーラ

最後に、私たちは自分のコードを公開したり、他の人にプロジェクトを使用したい、我々は別のプラットフォームのバイナリとソースファイルを提供したい。ここでは、この時間は第三のステップの前に設置されており、我々はいくつかの違いがあり、我々は我々が持っていることをインストールバイナリファイルのうち、ソースからの建物。この例では、我々はバイナリインストールとパッケージ管理はcygwinのは、debian、RPMのおよび他のツールを機能をサポートし、インストールパッケージを構築します。これを達成するために、我々は、作成するためにCPackを使用します。プラットフォーム関連のインストールパッケージ最後に、我々は次のように変更があり、CMakeLists.txtファイルのトップレベルにコードを追加する必要があります。

# build a CPack driven installer package
include (InstallRequiredSystemLibraries)
set (CPACK_RESOURCE_FILE_LICENSE  
     "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")
set (CPACK_PACKAGE_VERSION_MAJOR "${Tutorial_VERSION_MAJOR}")
set (CPACK_PACKAGE_VERSION_MINOR "${Tutorial_VERSION_MINOR}")
include (CPack)

次のように次の2つのステップがパッケージ化されています。

#针对二进制
cpack --config CPackConfig.cmake 
#针对源文件
cpack --config CPackSourceConfig.cmake

ステップ7:サポートCMakeListsを追加するためのダッシュボード

最後に、ダッシュボードにサポートを追加することは、我々は唯一のテストモジュールを追加する必要があるとdashboradに提出することができ、非常に簡単です。使用する上記テストモジュールは、一番上のCMakeLists.txtに次のコードを追加するために使用されます。

# enable dashboard scripting
include (CTest)

また、プロジェクト名を指定するCTestConfig.cmakeを追加する必要があります。これは次のように読み取ります。

set (CTEST_PROJECT_NAME "Tutorial")

最後に:

エラーがあるいくつかの場所では、テストを書きながら、最終的に完成し3日を書いて、私を修正してください。

参考リンク:

[1]: https://cmake.org/cmake-tutorial/
[2]: https://blog.csdn.net/fengzhongluoleidehua/article/details/79809756

おすすめ

転載: blog.csdn.net/ckkboy/article/details/97245342
おすすめ