首页 > 代码库 > C++一个项目里有两个CPP文件,想在一个CPP文件里调用另一个CPP文件的计算结果,怎么实现啊?

C++一个项目里有两个CPP文件,想在一个CPP文件里调用另一个CPP文件的计算结果,怎么实现啊?

把1.cpp和2.cpp放到同一目录下,例如:
1.cpp 代码如下
#include <iostream>

int main()
{
void ChangeFunction(int* input, int n);
void PrintData(int* input, int n);

int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
PrintData(a, 10);

ChangeFunction(a, 10);
PrintData(a, 10);

return 0;
}
2.cpp代码如下
#include <iostream>

void ChangeFunction(int* input, int n)
{
for (int i = 0; i < n; i++)
{
input[i] += 10;
}
}

void PrintData(int* input, int n)
{
std::cout << "=============================" << std::endl;
for (int i = 0; i < n; i++)
{
std::cout << input[i] << " ";
}
std::cout << std::endl;
std::cout << "-----------------------------" << std::endl;
}
输出结果:
=============================
1 2 3 4 5 6 7 8 9 10
----------------------------------------------
=============================
11 12 13 14 15 16 17 18 19 20
----------------------------------------------

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
C++里面是有头文件的,标准的做法是:头文件里面放函数声明,cpp放函数具体实现。按照你的描述应该可以用一个.h头文件放全部函数的声明,然后在1.cpp里放一个函数,2.cpp里放另一个函数,我们把1.cpp作为程序的入口,作为数据源,在这里调用2.cpp里的函数,这个函数返回计算结果。注意,两个cpp都要includ头文件

C++一个项目里有两个CPP文件,想在一个CPP文件里调用另一个CPP文件的计算结果,怎么实现啊?