<jupyter_start><jupyter_text>Introducing C/C++ * [**<NAME>**](https://en.wikipedia.org/wiki/Brian_Kernighan) and [**<NAME>**](https://en.wikipedia.org/wiki/Dennis_Ritchie), programmers of the [Bell Labs](https://en.wikipedia.org/wiki/Bell_Labs) published the first edition of the book on the [C Language](https://en.wikipedia.org/wiki/The_C_Programming_Language) in 1978.* [**Bjarne Stroustrup**](https://en.wikipedia.org/wiki/Bjarne_Stroustrup), a Danish computer scientist, started working on "C with Classes" in 1979, which he renamed to "C++" in 1983. * For example, following (procedural) code calculates sum from 1 to 100. ``` C++// include lines would embed .h header files// in this program, for the selected symbols// int32_t : 32bit integer -2^31 ~ +(2^31 - 1)include // printf() : a function to print on screeninclude // std::cout : an object to print on screeninclude // program start pointint32_t main(int32_t argn, char * argv[]){    // initalize s with zero    int32_t s = 0;    // int32_t means 32bit integer    // for loop    // i would start from 1 to 100    for (int32_t i=1; i<(100+1); ++i) {        // accumulate to s        s += i;    }    // present result    // this would work for both C and C++    printf("s = %d\n", s);    // present result    // this would only work for C++    std::cout << "s = " << s << '\n';    // indicate the program was successful    return 0;}```  Installing `g++` * `which g++`If `g++` not found, please try followings.* `su `* `sudo apt-get install g++`* `exit`* `which g++`Now we should be able to find the `g++`.  Writing and running a C/C++ program * Click following to start a tutorial. [![.cpp vi and terminal](https://i.ytimg.com/vi/7aG04VJZRMc/hqdefault.jpg)](https://youtu.be/7aG04VJZRMc) * `cd `* `vi hello.cpp`* i* Enter following code ``` C++include include int main(int argn, char * argv[]){    printf("Hello World!\n");    std::cout << "Hello World!" << '\n';        return 0;}``` * Esc`:wq`* `g++ -Wall -g hello.cpp -o hello && ./hello`  Compiling and running within `vi` * Click following to start a tutorial. (Caption available) [![within `vi`](https://i.ytimg.com/vi/SdQR9e6syxM/hqdefault.jpg)](https://youtu.be/SdQR9e6syxM) * Please start by entering `vi hello.cpp`* Press i to switch to insert mode.* Enter the source code.* When finished, press ESC to switch to command mode.* Enter `:w` to save the file.* Enter `:!g++ -Wall -g hello.cpp -o hello` to compile the file.If no error message, compile should have been successful.Press Enterto return to the `vi` editor.* Enter `:!./hello` to run the program.* Above two steps in one line : `:!g++ -Wall -g hello.cpp -o hello && ./hello`  Debugging using `gdb` [[ref](http://courses.cms.caltech.edu/cs11/material/c/mike/misc/gdb.html)] | action |           `gdb`           ||:------:|:-------------------------:|| start  | \$ `gdb ` || list commands | `h``help` || set break point at function `main`  | `b main` || start program  | `r``run` || step | `s` || evaluate 1 + 2 | `print 1 + 2` || evaluate `printf("Hello %d", 4 + 5)` | `print printf("Hello %d", 4 + 5)` || continue process | `c` || end debugger | `q` |  Building and debugging using MS VS Code * See [C/C++ for Visual Studio Code](https://code.visualstudio.com/docs/languages/cpp) for details.  Building a .cpp file in MS VS Code [![Building a .cpp in MS VS Code (Linux)](https://i.ytimg.com/vi/PQmJka_gLbE/hqdefault.jpg)](https://youtu.be/PQmJka_gLbE) * Please start by entering `code . &`* If not done yet, please install **Microsoft C/C++ extension**.Press Ctrl+Shift+x and search.* Open the Command Palate using Ctrl+Shift+p.* Select **Tasks: Configure Tasks...**.* Select **Create tasks.json file from template**.* Choose **Others**.* Change value of **command** to "`g++`" and add a comma at the end.* Add key "`args`" and its value as a bracket list as follows. [[ref0](https://stackoverflow.com/questions/45679035/build-currently-opened-file-in-visual-studio-code)],[[ref1](https://code.visualstudio.com/docs/editor/variables-reference)]`["-g", ${fileBasename}]`* To enable **Tasks: Run Build Task**, add "`group`" key-value pair.The tasks.json file would look as follows: ``` json {    "version": "2.0.0",    "tasks": [        {            "label": "build current file",            "type": "shell",            "command": "g++",            "args": [                "-Wall", "-g", "${fileBasename}",                 "-Wa,-adhln=${fileBasenameNoExtension}.s",            ],            "group": {                "kind": "build",                "isDefault": true            }        }    ]}```* To build, press Ctrl+Shift+b.  Debugging a .cpp file in MS VS Code [![Debugging a .cpp file in MS VS Code](https://i.ytimg.com/vi/_g2HxKdqB_I/hqdefault.jpg)](https://youtu.be/_g2HxKdqB_I) * To debug, press F5.* When `launch.json` appears, change the value of `"program"` to something like `"${workspaceFolder}/a.out"`.* Click on the left side of the row `int s = 0;` to set a break point.A red circle would appear.* Press F5.The debugger would wait for your command at the breakpoint.* Press F10.The debugger would move the highlight line to the next line.* Continue pressing F10.The debugger would update variables as the program executes.* To open console pane, press Ctrl+~.* Select `Debug Console` and enter a name of a variable to check its value.* If there is an iteration and you want to skip it, make another breakpoint after the loop and press F5.* To finish debugging press Shift+F5.* If you think it might be helpful, commit `tasks.json` and `launch.json` files into your repository. * Following is a sample `launch.json` for `(gdb) Launch` ``` json{    // Use IntelliSense to learn about possible attributes.    // Hover to view descriptions of existing attributes.    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387    "version": "0.2.0",    "configurations": [        {            "name": "(gdb) Launch",            "type": "cppdbg",            "request": "launch",            "program": "${workspaceFolder}/hello",            "args": [],            "stopAtEntry": false,            "cwd": "${workspaceFolder}",            "environment": [],            "externalConsole": true,            "MIMode": "gdb",            "setupCommands": [                {                    "description": "Enable pretty-printing for gdb",                    "text": "-enable-pretty-printing",                    "ignoreFailures": true                }            ],            "preLaunchTask": "make",        }    ]}```  Automating with Makefile * `g++` would build the executable file* Using `make` we can automate the process  Installing make * `which make`If `make` not found, please try followings.* `su `* `sudo apt-get install make``sudo apt-get install make-guile`* `exit`* `which make`Make sure that we can find the `make`.  Writing a Makefile * `cd `* `vi makefile`* i* Enter following code \[[ref0](http://courses.cms.caltech.edu/cs11/material/c/mike/misc/make.html), [ref1](http://mrbook.org/blog/tutorials/make/), [ref2](https://panthema.net/2013/0124-GCC-Output-Assembler-Code/), [ref3](https://stackoverflow.com/questions/10928966/make-multiple-targets-in-all), [ref4](https://stackoverflow.com/questions/16931770/makefile4-missing-separator-stop)\]note : all indentations are [Tab]. ``` makefileall : hello hello.shello : hello.cpp	g++ -Wall -g hello.cpp -o hellohello.s : hello.cpp	g++ -g hello.cpp -Wa,-adhln=hello.s clean :	rm hello hello.s``` * Esc`:wq`* `make`* `make hello.s`  Using variables in a Makefile * `cd `* `vi makefile`* i* Enter following codenote : all indentations are [Tab]. ``` makefileSRC = helloCPP = $(SRC).cppASM = $(SRC).sCC = g++all : $(SRC) $(ASM)$(SRC) : $(CPP)	$(CC) -Wall -g $(CPP) -o $(SRC)$(ASM) : $(CPP)	$(CC) -g $(CPP) -Wa,-adhln=$(ASM) clean :	rm $(SRC) $(ASM)``` * Esc`:wq`* `make clean`* `make hello.s`* `make`  Configuring MS VS Code to use the Makefile * Ctrl+Shift+b* Choose `Configure Build Task`* Choose `Open tasks.json file`* Configure as follows [[ref](https://code.visualstudio.com/docs/languages/cpp)] ``` json{    "version": "2.0.0",    "tasks": [        {            "label": "make",            "type": "shell",            "command": "make",            "group": {                "kind" : "build",                 "isDefault": true            }        }    ]}```  What is [JSON](https://en.wikipedia.org/wiki/JSON)? * JavaScript Object Notation* Open-standard file format* Human-readable* Attribute-value pairs and arrays  `build_util` module * `build_util` is an appendix of this material.  It can build a C++ source code and present the execution result as follows.<jupyter_code># build_util has functions to build and run C/C++ files within ipynb
import build_util.build_util as bu

# set .cpp filename
filename = 'hello_world.cpp'

# write c++ source code
bu.write_file(filename, r'''
#include <iostream>
#include <cstdio>

int main(int argn, char * argv[]){
    printf("Hello World!\n");
    std::cout << "Hello World!" << '\n';

    return 0;
}
''')

# build an execution file from the source
# would also generate an assembly code file
bu.build_cpp(filename)
# run execution file
bu.run(filename)
# remove source code file and execution file
bu.cleanup(filename)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16319706612015963, 'fraction_numerical': 0.015100852119512459, 'mean_word_length': 3.193577566711895, 'pattern_counts': {'":': 33, '<': 24, '<?xml version=': 0, '>': 9, 'https://': 22, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '646402', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 3026, 'n_tokens_neox': 2827, 'n_words': 985, 'path': '02.ipynb', 'repo_name': '2018pycpp/18pycpp-00', 'size': '9288'}