需要三个文件,调用函数所在cpp文件,被调用函数所在cpp文件,声明被调用函数的头文件。
第一个文件fibon_elem.cpp,包含fibon_elem函数,该函数用于产生斐波那契数列的第pos个值,并存于elem中,返回用户输入是否有效:
bool fibon_elem(int pos,int &elem) {
if(pos <= 0 || pos > 1024) {
elem = 0;
return false;
}
int first = 1,second = 1;
if(pos <= 2) {
elem = 1;
return true;
}
for(int i = 2;i < pos;i++) {
elem = first + second;
first = second;
second = elem;
}
return true;
}
第二个文件是code_list_2.1.h,声明被调用的函数:
bool fibon_elem(int ,int &);
第三个文件code_list_2.1.cpp,包含main函数,该函数调用fibon_elem函数:
#include <iostream>
#include "code_list_2.1.h" // important
using namespace std;
int main() {
int k = 0,pos = 0;
cout<<"plz enter a number between 0 to 1024." << endl;
cin>>pos;
if(fibon_elem(pos,k)) {
cout<<"the #" << pos << " element in the array is "<< k << endl;
} else {
cout<<"ooops, plz enter a number between 0 to 1024." << endl;
}
system("pause");
return 0;
}
关键在于编译时,要同时编译两个cpp文件,而按VS Code的官方配置,只会编译一个文件。解决办法是在tasks.json中修改:
"args": [
"-g", "code_list_2.1.cpp",
"-g", "fibon_elem.cpp"
]
将编译两个cpp文件的命令都加到args中去。
参考资料:
[1] 使用visual studio code 写C++ 怎么样才能正确地引用其他文件的函数 ButterFly的回答
手机扫一扫
移动阅读更方便
你可能感兴趣的文章