1
0

【備忘録】C++ のg++

Last updated at Posted at 2024-03-23

CPPコードを実装するにはg++コマンドを使ってcompileしMachine言語(0と1)に変換しますが、そのプロセス背景で起きていることを備忘録としてまとめます。

image.png

1)Preprocessing: Preprocessorが#includeや#defineで定義されたLibraryのソースコードを準備
Command: 'gcc -E main.cpp -o main.i'

2) Compilation: Compilerが書いたCPPコードとPreprocessされたコードをAssembly言語へ変換する(Processor Architectureに応じる)
Command: 'gcc -S main.i -o main.s'

3) Assembly: AssemblerがAssembly言語化されたコードをMachine言語へ変換する(.oや.objのオブジェクトファイル)このファイルは単独実装一歩手前
Command: 'gcc -c main.s -o main.o'

4)Linking: Linkerがオブジェクトファイルと上述のLibraryを繋げ、Executable(Windowsなら.exe、MacやLinuxならa.out)を作る
Command: 'gcc main.o -o hello_world'

このプロセスは、CMakeLists .txtで簡素化・代替でき、

・まず、現在のDirに’CMakeLists.txt’を作る

cmake_minimum_required(VERSION 3.10)
project(HelloWorld)
set(CMAKE_CXX_STANDARD 11)
add_executable(hello_world main.cpp)

・'mkdir build & cd build'で’build' dirを作り移動

・'cmake ..'で先のCMakeLists.txtを元に、Makefileをbuild内に作成

all: hello_world

hello_world: main.o
	g++ main.o -o hello_world

main.o: main.cpp
	g++ -c main.cpp -o main.o

・最後にmakeで以下4ステップを実装:
ーPreprocessing: g++ -E main.cpp -o main.i (handled internally)
ーCompilation: g++ -c main.cpp -o main.o
ーAssembly: Part of the compilation step
ーLinking: g++ main.o -o hello_world

1
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
1
0