


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); }
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
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
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
Enter the program name on the command line to run it:
$ ./helloworld hello, world
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
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
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 *); };
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"; }
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); }
The following command compiles and links the above two source code files into a single executable program:
$ g++ hellospeak.cpp speak.cpp -o hellospeak
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
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
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
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
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
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
生成的汇编语言依赖于编译器的目标平台。
创建静态库
静态库是编译器生成的一系列对象文件的集合。链接一个程序时用库中的对象文件还是目录中的对象文件都是一样的。库中的成员包括普通函数,类定义,类的对象实例等等。静态库的另一个名字叫归档文件(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); };
下面是文件 say.cpp 是我们要加入到静态库中的两个对象文件之一的源码。它包含 Say 类中 sayString() 函数的定义体;类 Say 的一个实例 librarysay 的声明也包含在内:
/* say.cpp */ #include "say.h" void Say::sayString() { std::cout << string << "\n"; } Say librarysay("Library instance of Say");
源码文件 sayhello.cpp 是我们要加入到静态库中的第二个对象文件的源码。它包含函数 sayhello() 的定义:
/* sayhello.cpp */ #include "say.h" void sayhello() { std::cout << "hello from a static library\n"; }
下面的命令序列将源码文件编译成对象文件,命令 ar 将其存进库中:
$ g++ -c sayhello.cpp $ g++ -c say.cpp $ ar -r libsay.a sayhello.o say.o
程序 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); }
该程序可以下面的命令来编译和链接:
$ g++ saymain.cpp libsay.a -o saymain
程序运行时,产生以下输出:
hello from a static library howdy from a static library Library instance of Say Local instance of Say
ps:如果一个文件夹下有多个cpp文件需要编译的话,除了采用makefile的方式之外,还可以使用“g++ *.cpp -o hello",“hello为编译生成的可执行文件的名字”,编译时要确保cpp文件和他们各自所引用的头文件在同一个目录下。
相关推荐:
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!

Linux maintenance mode is entered by adding init=/bin/bash or single parameters at startup. 1. Enter maintenance mode: Edit the GRUB menu and add startup parameters. 2. Remount the file system to read and write mode: mount-oremount,rw/. 3. Repair the file system: Use the fsck command, such as fsck/dev/sda1. 4. Back up the data and operate with caution to avoid data loss.

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

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

When choosing a Hadoop version suitable for Debian system, the following key factors need to be considered: 1. Stability and long-term support: For users who pursue stability and security, it is recommended to choose a Debian stable version, such as Debian11 (Bullseye). This version has been fully tested and has a support cycle of up to five years, which can ensure the stable operation of the system. 2. Package update speed: If you need to use the latest Hadoop features and features, you can consider Debian's unstable version (Sid). However, it should be noted that unstable versions may have compatibility issues and stability risks. 3. Community support and resources: Debian has huge community support, which can provide rich documentation and

This article describes how to use TigerVNC to share files on Debian systems. You need to install the TigerVNC server first and then configure it. 1. Install the TigerVNC server and open the terminal. Update the software package list: sudoaptupdate to install TigerVNC server: sudoaptinstalltigervnc-standalone-servertigervnc-common 2. Configure TigerVNC server to set VNC server password: vncpasswd Start VNC server: vncserver:1-localhostno

Configuring a Debian mail server's firewall is an important step in ensuring server security. The following are several commonly used firewall configuration methods, including the use of iptables and firewalld. Use iptables to configure firewall to install iptables (if not already installed): sudoapt-getupdatesudoapt-getinstalliptablesView current iptables rules: sudoiptables-L configuration

The steps to install an SSL certificate on the Debian mail server are as follows: 1. Install the OpenSSL toolkit First, make sure that the OpenSSL toolkit is already installed on your system. If not installed, you can use the following command to install: sudoapt-getupdatesudoapt-getinstallopenssl2. Generate private key and certificate request Next, use OpenSSL to generate a 2048-bit RSA private key and a certificate request (CSR): openss

Configuring a virtual host for mail servers on a Debian system usually involves installing and configuring mail server software (such as Postfix, Exim, etc.) rather than Apache HTTPServer, because Apache is mainly used for web server functions. The following are the basic steps for configuring a mail server virtual host: Install Postfix Mail Server Update System Package: sudoaptupdatesudoaptupgrade Install Postfix: sudoapt


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft