Home Operation and Maintenance Linux Operation and Maintenance How to compile C++ using g++ under Linux

How to compile C++ using g++ under Linux

Mar 26, 2018 am 09:32 AM
linux use method

This article mainly shares with you the method of compiling C++ with g++ in the Linux environment and related example code sharing. Friends who are interested can learn from it. Hope it helps everyone.

A single source file generates an executable program

The following is the code of a simple C++ program saved in the file helloworld.cpp:


/* helloworld.cpp */
#include <iostream>
int main(int argc,char *argv[])
{
  std::cout << "hello, world" << std::endl;
  return(0);
}
Copy after login

The program uses cout defined in the header file iostream to write a simple string to the standard output. This code can be compiled into an executable file with the following command:


$ g++ helloworld.cpp
Copy after login

The compiler g++ can identify a C++ source code file by checking its suffix name on the file specified on the command line. The default action of the compiler: compile the source code file to generate an object file (object file), link the object file and the functions in the libstdc++ library to obtain an executable program. Then delete the object file. Since the file name of the executable program is not specified on the command line, the compiler uses the default a.out. The program can be run like this:


$ ./a.out
hello, world
Copy after login

A more common approach is to specify the file name of the executable program through the -o option. The following command will produce an executable file named helloworld:


$ g++ helloworld.cpp -o helloworld
Copy after login

Enter the program name on the command line to run it:


$ ./helloworld
hello, world
Copy after login

The program g++ is a special version that sets the default language of gcc to C++. It automatically uses the C++ standard library instead of the C standard library when linking. By following the naming convention of the source code and specifying the name of the corresponding library, it is feasible to use gcc to compile and link C++ programs, as shown in the following example:


$ gcc helloworld.cpp -lstdc++ -o helloworld
Copy after login

Option -l (ell ) transforms the name following it into the name of the library libstdc++.a by adding the prefix lib and the suffix .a. Then it looks for the library in the standard library path. The compilation process and output files of gcc are exactly the same as those of g++.

In most systems, a program called c++ is installed when GCC is installed. If installed, it is equivalent to g++, as shown in the following example, and its usage is consistent:


$ c++ helloworld.cpp -o helloworld
Copy after login

Multiple source files generate executable programs

If more than one source code file is specified in the g++ command, they will all be compiled and linked into a single executable file. The following is a header file named speak.h; it contains the definition of a class that contains only one function:


/* speak.h */
#include <iostream>
class Speak
{
  public:
    void sayHello(const char *);
};
Copy after login

Listed below is the file speak.cpp Content: The function body containing the sayHello() function:


/* speak.cpp */
#include "speak.h"
void Speak::sayHello(const char *str)
{
  std::cout << "Hello " << str << "\n";
}
Copy after login

The file hellospeak.cpp is a program using the Speak class:


/* hellospeak.cpp */
#include "speak.h"
int main(int argc,char *argv[])
{
  Speak speak;
  speak.sayHello("world");
  return(0);
}
Copy after login

The following command compiles and links the above two source code files into a single executable program:


$ g++ hellospeak.cpp speak.cpp -o hellospeak
Copy after login

PS: Let’s talk about why in the command The file "speak.h" is not mentioned in (the reason is: "speak.cpp" contains the code "#include "speak.h"", which means that the system header file directory will be searched before Search for the file "speak.h" in the current directory. "speak.h" is in this directory and does not need to be specified in the command).

Source file generates object file

The -c option is used to tell the compiler to compile the source code but not to perform linking, and the output result is an object file. The default file name is the same as the source file name, except that the suffix is ​​changed to .o. For example, the following command will compile the source file hellospeak.cpp and generate the object file hellospeak.o:


$ g++ -c hellospeak.cpp
Copy after login

The command g++ can also recognize .o files and use them as input files passed to the linker. The following command will compile source files into object files and link them into a single executable program:


$ g++ -c hellospeak.cpp 
$ g++ -c speak.cpp 
$ g++ hellospeak.o speak.o -o hellospeak
Copy after login

The option -o can be used to name more than just executable files. It is also used to name other files output by the compiler. For example: The following command will generate exactly the same executable file as above except that the intermediate object files have different names:


$ g++ -c hellospeak.cpp -o hspk1.o 
$ g++ -c speak.cpp -o hspk2.o 
$ g++ hspk1.o hspk2.o -o hellospeak
Copy after login

Compilation Preprocessing

Option -E causes g++ to process the source code with the compilation preprocessor without performing other actions. The following command preprocesses the source code file helloworld.cpp and displays the results in the standard output:


$ g++ -E helloworld.cpp
Copy after login

The source code of helloworld.cpp listed earlier in this article only has Six lines, and the program does nothing but display a line of text, but the preprocessed version will be over 1200 lines. This is mainly because the header file iostream is included, and it contains other header files. In addition, there are definitions of several classes that handle input and output.

The GCC suffix of the preprocessed file is .ii, which can be generated through the -o option, for example:


$ gcc -E helloworld.cpp -o helloworld.ii
Copy after login

Generate assembly Code

option -S instructs the compiler to compile the program into assembly language, output the assembly language code and then end. The following command will generate the assembly language file helloworld.s from the C++ source code file:


$ g++ -S helloworld.cpp
Copy after login

生成的汇编语言依赖于编译器的目标平台。

创建静态库

静态库是编译器生成的一系列对象文件的集合。链接一个程序时用库中的对象文件还是目录中的对象文件都是一样的。库中的成员包括普通函数,类定义,类的对象实例等等。静态库的另一个名字叫归档文件(archive),管理这种归档文件的工具叫 ar 。

在下面的例子中,我们先创建两个对象模块,然后用其生成静态库。

头文件 say.h 包含函数 sayHello() 的原型和类 Say 的定义:


/* say.h */
#include <iostream>
void sayhello(void);
class Say {
  private:
    char *string;
  public:
    Say(char *str)
    {
      string = str;
    }
    void sayThis(const char *str)
    {
      std::cout << str << " from a static library\n";
    }
    void sayString(void);
};
Copy after login

下面是文件 say.cpp 是我们要加入到静态库中的两个对象文件之一的源码。它包含 Say 类中 sayString() 函数的定义体;类 Say 的一个实例 librarysay 的声明也包含在内:


/* say.cpp */
#include "say.h"
void Say::sayString()
{
  std::cout << string << "\n";
}
 
Say librarysay("Library instance of Say");
Copy after login

源码文件 sayhello.cpp 是我们要加入到静态库中的第二个对象文件的源码。它包含函数 sayhello() 的定义:


/* sayhello.cpp */
#include "say.h"
void sayhello()
{
  std::cout << "hello from a static library\n";
}
Copy after login

下面的命令序列将源码文件编译成对象文件,命令 ar 将其存进库中:


$ g++ -c sayhello.cpp
$ g++ -c say.cpp
$ ar -r libsay.a sayhello.o say.o
Copy after login

程序 ar 配合参数 -r 创建一个新库 libsay.a 并将命令行中列出的对象文件插入。采用这种方法,如果库不存在的话,参数 -r 将创建一个新的库,而如果库存在的话,将用新的模块替换原来的模块。

下面是主程序 saymain.cpp,它调用库 libsay.a 中的代码:


/* saymain.cpp */
#include "say.h"
int main(int argc,char *argv[])
{
  extern Say librarysay;
  Say localsay = Say("Local instance of Say");
  sayhello();
  librarysay.sayThis("howdy");
  librarysay.sayString();
  localsay.sayString();
  return(0);
}
Copy after login

该程序可以下面的命令来编译和链接:


$ g++ saymain.cpp libsay.a -o saymain
Copy after login

程序运行时,产生以下输出:


hello from a static library
howdy from a static library
Library instance of Say
Local instance of Say
Copy after login

ps:如果一个文件夹下有多个cpp文件需要编译的话,除了采用makefile的方式之外,还可以使用“g++ *.cpp -o hello",“hello为编译生成的可执行文件的名字”,编译时要确保cpp文件和他们各自所引用的头文件在同一个目录下。

相关推荐:

在Linux环境下g++编译GDAL动态库的操作方法

Linux下g++编译以及使用静态库和动态库的方法详解

Linux下如何实现C++操作Mysql数据库的详细介绍


The above is the detailed content of How to compile C++ using g++ under Linux. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to start apache How to start apache Apr 13, 2025 pm 01:06 PM

The steps to start Apache are as follows: Install Apache (command: sudo apt-get install apache2 or download it from the official website) Start Apache (Linux: sudo systemctl start apache2; Windows: Right-click the "Apache2.4" service and select "Start") Check whether it has been started (Linux: sudo systemctl status apache2; Windows: Check the status of the "Apache2.4" service in the service manager) Enable boot automatically (optional, Linux: sudo systemctl

What to do if the apache80 port is occupied What to do if the apache80 port is occupied Apr 13, 2025 pm 01:24 PM

When the Apache 80 port is occupied, the solution is as follows: find out the process that occupies the port and close it. Check the firewall settings to make sure Apache is not blocked. If the above method does not work, please reconfigure Apache to use a different port. Restart the Apache service.

How to restart the apache server How to restart the apache server Apr 13, 2025 pm 01:12 PM

To restart the Apache server, follow these steps: Linux/macOS: Run sudo systemctl restart apache2. Windows: Run net stop Apache2.4 and then net start Apache2.4. Run netstat -a | findstr 80 to check the server status.

How to solve the problem that apache cannot be started How to solve the problem that apache cannot be started Apr 13, 2025 pm 01:21 PM

Apache cannot start because the following reasons may be: Configuration file syntax error. Conflict with other application ports. Permissions issue. Out of memory. Process deadlock. Daemon failure. SELinux permissions issues. Firewall problem. Software conflict.

How to learn Debian syslog How to learn Debian syslog Apr 13, 2025 am 11:51 AM

This guide will guide you to learn how to use Syslog in Debian systems. Syslog is a key service in Linux systems for logging system and application log messages. It helps administrators monitor and analyze system activity to quickly identify and resolve problems. 1. Basic knowledge of Syslog The core functions of Syslog include: centrally collecting and managing log messages; supporting multiple log output formats and target locations (such as files or networks); providing real-time log viewing and filtering functions. 2. Install and configure Syslog (using Rsyslog) The Debian system uses Rsyslog by default. You can install it with the following command: sudoaptupdatesud

Does the internet run on Linux? Does the internet run on Linux? Apr 14, 2025 am 12:03 AM

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

How to fix apache vulnerability How to fix apache vulnerability Apr 13, 2025 pm 12:54 PM

Steps to fix the Apache vulnerability include: 1. Determine the affected version; 2. Apply security updates; 3. Restart Apache; 4. Verify the fix; 5. Enable security features.

How to start nginx in Linux How to start nginx in Linux Apr 14, 2025 pm 12:51 PM

Steps to start Nginx in Linux: Check whether Nginx is installed. Use systemctl start nginx to start the Nginx service. Use systemctl enable nginx to enable automatic startup of Nginx at system startup. Use systemctl status nginx to verify that the startup is successful. Visit http://localhost in a web browser to view the default welcome page.

See all articles