参考:VSCode配置 c++ 环境(小白教程)
/** ex01_main().cpp
Create a header file (with an extension of ‘.h’). In this file,
declare a group of functions by varying the argument lists and
return values from among the following: void, char, int, and float.
Now create a .cpp file that includes your header file and creates
definitions for all of these functions. Each definition should simply
print out the function name, argument list, and return type so you know
it’s been called. Create a second .cpp file that includes your header
file and defines int main( ), containing calls to all of your functions.
**/
#include
#include "ex01_header.h"
using namespace std;
int main() {
func1(2 , 2.2);
func2();
func3(3);
func4(4.6, 'z');
system("pause");
return 0;
}
#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
void func1(int , double );
char func2();
int func3(int );
float func4(double , char);
#endif // HEADER_H_INCLUDED
#include
#include "ex01_header.h"
using namespace std;
void func1(int x, double y) {
cout << "Called func1(" << x << ", " << y << "), returns void." << endl;
}
char func2() {
cout << "Called func2(), returns char." << endl;
}
int func3(int x) {
cout << "Called func3(" << x << "), returns int." << endl;
}
float func4(double a, char b) {
cout << "Called func4("<< a << ", " << b << "), returns float." << endl;
}
d:/mingw/bin/…/lib/gcc/mingw32/9.2.0/…/…/…/…/mingw32/bin/ld.exe: d:/Research/David/Thinking in C++/EckelCpp-master/Volume 1/3. C and CPP/cpp_source/ex01/ex01_main.cpp:20: undefined reference to `func2()'
d:/mingw/bin/…/lib/gcc/mingw32/9.2.0/…/…/…/…/mingw32/bin/ld.exe: d:/Research/David/Thinking in C++/EckelCpp-master/Volume 1/3. C and CPP/cpp_source/ex01/ex01_main.cpp:21: undefined reference to `func3(int)'
d:/mingw/bin/…/lib/gcc/mingw32/9.2.0/…/…/…/…/mingw32/bin/ld.exe: d:/Research/David/Thinking in C++/EckelCpp-master/Volume 1/3. C and CPP/cpp_source/ex01/ex01_main.cpp:22: undefined reference to `func4(double, char)'
报错信息均提到未定义头文件中的函数,也就是说ex01_header.cpp头文件没有编译成功。但是头文件已经放进工作目录里了,main文件也对头文件进行了预处理#include “ex01_header.h”。
那么到底是什么原因导致编译不成功呢?
在网上查找了许多资料无果后,我转换了思考的角度,开始从程序最基本的编译过程考虑问题。
首先简单看一下程序编译过程:
预处理:主要把是进行宏展开、声明头文件当中函数的过程
编译:主要是进行语法检查和分析,确保函数和数据正确使用
链接:主要是将编译生成的目标模块连接成系统可加载和执行的程序
既然是头文件没有被编译成功,那么应该是编译这个过程出现了问题。
Emacs编辑器的使用在这里不详细介绍,感兴趣的自行查找资料。
在这里我想说的是,在Emacs编辑器中编译时需要包含头文件ex01_header.cpp才能编译成功,需输入以下命令:
g++ ex01_main.cpp ex01_header.cpp -o myex_01 -g
可以看到,文件ex01_main.cpp和ex01_header.cpp都需要被编译才能运行成功。
那么在VS code里,理论上也要编译ex01_header.cpp文件
VS code C++的编译器参数配置参考:VSCode配置 c++ 环境(小白教程)
编译命令参数在tasks.json文件中:
"args": [
"-g",
"${file}", //这里是被编译的文件
"-o",
"${workspaceFolder}/exe/${fileBasenameNoExtension}.exe"
], // 编译命令参数
要把ex01_header.cpp加进去只需添加一行文件路径,如下:
"args": [
"-g",
"${file}",
"d:/Research/David/Thinking in C++/EckelCpp-master/Volume 1/3. C and CPP/cpp_source/ex01/ex01_header.cpp",
"-o",
"${workspaceFolder}/exe/${fileBasenameNoExtension}.exe"
], // 编译命令参数