Learning C++ Notes in Ubuntu

Refer to the video tutorial at station B: C++ compiler installation under ubuntu system for zero-based learning of Linux programming_哔哩哔哩_bilibili

Chapter 1 Development Environment Construction

1. Commonly used compilers:

  • g++

    • $ g++ test001.cpp -o hello # -o to name the file as hello
      $ ./hello
  • gcc

    • Note that if it is used to compile c++ files, when using the std library, it should be written as:

    • $ gcc test001.cpp -lstdc++ -o hello
  • clang

    • $ clang++ test001.cpp -o hello
      # 或:
      $ clang test001.cpp -lstdc++ -o hello
    • Pay attention to the version of clang, it is recommended not to use the default version 6.0

  • cmake

    • To use cmake, first create a folder, in this example hello_project   

    • $ mkdir hello_project
      $ cd hello_project/
      ./hello_project$ touch CMakeLists.txt
    • Edit in CMakeLists.txt as follows:

      • #CMakeLists.txt    //filename
        PROJECT(hello_project)    // project name
        ADD_EXECUTABLE(hello test001.cpp)    //exe name and the cpp name
    • Then type in the terminal:

      • ./hello_project$ cmake .    # . 表示当前目录
        ./hello_project$ make
        ./hello_project$ ./hello
    • If you don't want to write the command number, you can also write it in the GUI

      • $ cmake-gui

2. CMake common commands

  • Common process

    • The above process is too simple, and the generated files are messy, here is the common process:

      1. Create a project folder: hello_project

      2. Create basic folders and files in the project folder:

        • folder: build

        • File: CMakeLists.txt

          #CMakeLists.txt    #文件名称
          cmake_minimum_required (VERSION 3.10.2)    
          #规定最低版本
          PROJECT(hello_project)    #项目名称
          ADD_SUBDIRECTORY(src)    #添加子目录
        • Folder: src, which contains files:

          • Code file: test001.cpp

          • CMakeList.txt

            #CMakeLists.txt
            ADD_EXECUTABLE(hello test001.cpp)
      3. Open a terminal in the build folder:

        $ cmake ..    # .. 表示CMakeLists.txt文件在上一层目录
        $ make

        At this point, the hello executable file appears in the src folder in the build

        $ ./hello
    • Another way to write CMakeLists.txt: just write the one CMakeLists.txt in the project folder:

      #CMakeLists.txt    #文件名称
      cmake_minimum_required (VERSION 3.10.2)    
      #规定最低版本
      PROJECT(hello_project)    #项目名称
      #include_directories(./src)    # 包含src文件夹,这句有没有都可以
      aux_source_directory(./src SRCS)    # 将src目录下所有源文件添加到SRCS变量中
      ADD_EXECUTABLE(hello ${SRCS})    # 将SRCS中的文件编译成一个可执行文件
      • Note that when copying the above content, there will be spaces at the end of each line. If you compile directly, the following error will occur:
      Parse error.  Expected a command name, got unquoted argument with textu

      After writing the file, enter in the build folder:

      $ cmake ..
      $ make
      $ ./hello

3. Development tool-vscode

  • Installation steps omitted

  • The command line opens:

    $ code
  • To install C/C++, CMake plugin

  • You can compile in the same way as above in the terminal of vscode

4. Install Qt5

(process omitted)

5. Code comments and breakpoint debugging

(The video is all about the operations in clion)

6. Development Documentation

C++ Standard Library Reference | Microsoft Docs

C Runtime Library Reference | Microsoft Docs

Chapter 2 Basic Grammar of C++

1. Definition and call of classes and methods

  • In the same folder, write a .h file for declaration, and write a .cpp with the same name to implement the method in the .h file

  • Example:

    • demo.h file:

      //定义类Demo
      class Demo
      {
          public:    // 公开访问
              void Hello(const char *);
              //定义方法Hello,void代表没有返回值
      };//注意这里有个分号
    • demo.cpp file:

      #include "demo.h"
      #include <iostream>
      using namespace std;
      
      void Demo::Hello(const char *str)
      {
          cout << "Hello, Demo " << str << "\n";
      }
    • Call this class in the program demo_test.cpp:

      # include "demo.h"    //包含类头文件
      
      int main(int argc, char *argv[]){
          Demo objDemo;    //定义Demo对象
          objDemo.Hello("world");    //调用成员函数Hello,传入参数world
          return 0;
      }
    • Compile with g++:

      $ g++ demo_test.cpp demo.cpp -o demo
      $ ./demo

2. Non-class method writing and variable definition

(That is, the process of commonly used writing methods can be written directly in the program file instead of in a separate file)

3. Variables - declaration and initialization

  • The variables written in the method are local variables, and the variables written outside the method are global variables

4. Use GDB to call C++ program for debugging

  • # 生成可执行文件时,要加个-g 
    $ g++ -g demo_test.cpp demo.cpp -o demo
    $ gdb demo # 使用gdb运行一下
    $ # 显示reading symbols from demo 表示可以正常读取程序的索引符号
    $ (gdb) b 14 # 在14行设置断点
    $ (gdb) b 15 # 在15行设置断点
    $ (gdb) r    # 启动程序,此时会停在断点14行
    $ (gdb) s # 进入当前类的方法里
    $ (gdb) print(str)    #在当前类的位置打印变量值
  • Instruction meaning:

    Order explain example
    file <filename> Load the executable program file to be debugged. Because GDB is generally executed in the directory where the debugged program is located, the text name does not need to have a path (gdb) file gdb-sample
    r Short for Run, run the program being debugged. If no breakpoint has been set before, the entire program is executed; if there is a breakpoint, the program pauses at the first available breakpoint. (gdb) r
    c Shorthand for Continue, continue to execute the debugged program until the next breakpoint or the end of the program (gdb) c
    b <line number>
    b <function name>
    b *<function name>
    b *<code address>
    b: Shorthand for Breakpoint, set a breakpoint. Two, you can use "line number", "function name", "execution address" and other ways to specify the breakpoint position.
    Among them, adding a "*" symbol in front of the function name indicates that the breakpoint is set at "the prolog code generated by the compiler".
    If you don't know assembly, you can ignore this usage.
    (gdb) b 8

    (gdb) b main

    (gdb) b *main

    (gdb) b *0x804835c
    d [number] d: Shorthand for Delete breakpoint, delete a breakpoint with a specified number, or delete all breakpoints. Breakpoint numbers start at 1 and increment. (gdb) d
    s,n s: Execute a line of source code, if there is a function call in this line of code, enter the function;

    n: Execute a line of source code, and the function call in this line of code is also executed.

    s is equivalent to "Step Into" in other debuggers;

    n is equivalent to "Step Over" in other debuggers.

    These two commands can only be used when there is source code debugging information (use the "-g" parameter when compiling with GCC).
    (gdb) s

    (gdb) n
    si, ni The si command is similar to the s command, and the ni command is similar to the n command. The difference is that these two commands (si/ni) are aimed at assembly instructions, while s/n is aimed at source code. (gdb) si

    (gdb) by
    p Shorthand for Print, which displays the value of a specified variable (temporary or global). (gdb) p i

    (gdb) p nGlobalVar
    display ...
    undisplay <number> display, set the data and its format to be displayed after the program is interrupted.

    For example, if you want to see the next assembly instruction to be executed every time the program is interrupted, you can use the command
    "display /i pc" where pc represents the current assembly instruction, and /i means to display in sixteen. This command is useful when you need to care about assembly code.
    undispaly, cancel the previous display setting, and the number will increase from 1. (gdb) display /i $pc

    (gdb) undisplay 1
    i Shorthand for Info, used to display various information, please refer to "help i" for details. (gdb) i r
    q Shorthand for Quit, exit the GDB debugging environment. (gdb) q
    help [command name] GDB help command, providing explanations for GDB name commands.

    If the "command name" parameter is specified, the detailed description of the command will be displayed; if no parameter is specified, all GDB commands will be displayed in categories for users to further browse and query.
    (gdb) help display

5. cin/getline/stringstream

cin in C++ and stringstream_flow_specter's blog - CSDN Blog

Use a delimiter to indicate the end of an input. cinAfter the read is successful, the delimiter after the character remains in the buffer and cin>>is not processed
. The delimiter is:

  1. Space (space)
  2. tab(tab)
  3. 换行(new-line character)
    但是,如果缓冲区中的第一个字符是分隔符时,cin会将其忽略并清除
// i/o example

#include <iostream>
using namespace std;

int main ()
{
  int i;
  cout << "Please enter an integer value: ";
  cin >> i;
  cout << "The value you entered is " << i;
  cout << " and its double is " << i*2 << ".\n";
  return 0;
}

输出为:

Please enter an integer value: 702
The value you entered is 702 and its double is 1404.

但是,如果键盘输入的i不是int类型呢?那么就会导致错误,导致i没有被正确的赋值。stringstreams则会更好的处理这种情况。

notes: Most programs are expected to behave in an expected manner no matter what the user types, handling invalid values appropriately.

cin>>a>>b

等价于:

cin >> a;
cin >> b;

cin and strings

cin也可以用来读取string

string mystring;
cin >> mystring;

但是,我们知道cin经常会处理分隔符,因此在此就限制了string只能是连续的word,而不能是phrase 或者sentence。

为了进一步的能够通过cin输入一段phrase或者sentence,引入了一个新的函数:getline,该函数接收两个参数,第一个参数为cin,第二个参数则为string变量,见以下示例:

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr); //第一个变量是cin,第二个是string变量
  cout << "Hello " << mystr << ".\n";
  cout << "What is your favorite team? ";
  getline (cin, mystr); // 在第二次使用getline的时候,程序只是简单的replace the previous content with the new one that is introduced.
  cout << "I like " << mystr << " too!\n";
  return 0;
}

输出为:

What's your name? Homer Simpson
Hello Homer Simpson.
What is your favorite team? The Isotopes
I like The Isotopes too!

此时,逐行的换行通过 press ENTER(or RETURN)来实现。

notes: Unless you have a strong reason not to, you should always use getline to get input in your console programs instead of extracting from cin.

stringstream

The standard header files <sstream>define a type called stringstream that allows strings to be treated as streams, allowing strings to be extracted from or inserted into in the same way as is done on cin and cout.

This function is very useful for converting between strings and numbers , that is, you can get values ​​from standard input indirectly. For example, to convert a string to a number:

string mystr ("1204");
int myint;
stringstream(mystr) >> myint;

Another example:

// stringstreams
#include <iostream>
#include <string>
#include <sstream>
using namespace std;

int main ()
{
  string mystr;
  float price=0;
  int quantity=0;

  cout << "Enter price: ";
  getline (cin,mystr);
  stringstream(mystr) >> price;
  cout << "Enter quantity: ";
  getline (cin,mystr);
  stringstream(mystr) >> quantity;
  cout << "Total price: " << price*quantity << endl;
  return 0;
}

The output is:

Enter price: 22.25
Enter quantity: 7
Total price: 155.75

The advantage of this over directly using cinthe input value is that
by this method of getting the entire line and extracting its content, the process of getting user input is separated from the two-step operation of assigning it to a value variable.

  • cin/getline/getchar usage and difference

    int a = 0;
    string b = {0};
    string c = "";
    printf("请输入一个字符(getchar):\n");
    a = getchar();
    printf(“你输入的是:%d\n”,a-48);
    getchar();    // 用来等待回车(或任意键)

    printf("Please enter a character (getline):\n"); getline(cin,b); printf("You entered: %s\n", b.c_str()); //b.c_str( ) getchar(); // used to wait for carriage return (or any key)

    printf("Please enter a character (cin):\n"); cin >> c; printf("You entered: %s\n",c); getchar(); // used to wait for carriage return ( or any key)

6. Use vscode for breakpoint debugging

  • To install plugin C/C++

7. sleep() is in the header file unistd.h

  • In linux, the unit in brackets is seconds

8. goto statement (unconditional transfer)

> #include<stdio.h>
> int main (void){
>     int n;
>     pos_1:
>         printf("请输入一个正整数:");
>         scanf("%d",&n);
>         if(n<0)
>         {
>             printf("输入错误!\n");
>             goto pos_1;
>         }
>         printf("成功输入正整数:%d\n",n);
>         return 0;
> }

Guess you like

Origin blog.csdn.net/aniclever/article/details/123224997