资料来源:南科大 于仕琪 C/C++ Program Design
LINK:CPP/week01 at main · ShiqiYu/CPP · GitHub
本节内容
- Download and install GCC on Windows 10 (Based on Windows Subsystem for Linux)
- Download and install the editor (VSCode)
- Compile, link and run C/C++ programs
- Set output format
收获
- 在Linux下开发C++比较快捷,因此连用WSL和VScode是一个很好的选择。
- 多个相互链接的CPP,编译时,确保将依赖的文件放在主程序的左边。否则编译时会出现没有编译出所调用的.o文件而报错。
正确编译命令:
g++ -c main.cpp add.cpp
g++ -o main main.cpp add.cpp
部分习题笔记
习题6.2
Copy the following code into 3 files, and compile them together to an executable file. Find the bugs if there are some.
Step 1: Compile main.cpp
Step 2: Compile add.cpp
Step 3: Link the two object files.
Note
- 注意变量类型对应取值范围
- 注意分号
- 注意函数名称要一致
Answer
main.cpp
#include <iostream>
#include "add.h"
using namespace std;
int main()
{
long num1 = 2147483647;
long num2 = 1;
long result = 0;
result = add(num1, num2);
cout << "The result is" << result << endl;
return 0;
}
add.h
#pragma once
long add(long n1, long n2);
add.cpp
#include "add.h"
long add(long number1, long number2)
{
return number1 + number2;
}