包含并运行来自其他文件的函数

Include and run function from other file

本文关键字:文件 函数 其他 运行 包含      更新时间:2023-10-16

我有 2 个文件,main.cpp 和 xyz.cpp,xyz.cppp 具有进行一些计算的功能(并且应该在最后输出它(,我想从 main 中的开关调用这个函数.cpp

主要.cpp :

#include <iostream>
#include <math.h>
#include <cstdlib> 
#include "xyz.cpp"
int cl;
using namespace std;
int main(int argc, const char * argv[]){
cout << ("Make ur choice (1-1)");
cin >> cl;
switch(cl){
case (1):{
// I suppose it should be called here somehow 
}
}
return 0;
}

xyz.cpp:


using namespace std;
int function() {

cout << "Input number: "; 
cin >> a; 

o1p1 = (1+cos(4*a)); 
o1p2 = (1+cos(2*a)); 

o1 = ((sin(4*a))/o1p1)*((cos(2*a))/o1p2);   
cout << "nZ1 = ";
cout << o1; 
cout << "n "; 
return 0;
}

在你有评论的地方,只需写:

function();

但是,请注意,通常您希望包含文件(即具有函数声明的文件(,而不是源文件(具有定义的文件(。

在标题中,您将有:

int function();

源文件将是相同的。

请注意,这意味着您必须编译两个源文件,而不仅仅是主文件。

重命名方法,否则调用将不明确。

使用名为"xyz.h"的头文件,在其中声明方法。然后,在主.cpp文件中,包含该头文件(而不是其源文件(。源文件"xyz.cpp"也应包含头文件。然后在main.cpp中,只需像这样调用方法:int returnedValue = myFunction();

完整示例:

xyz.h

#ifndef XYZ_H
#define XYZ_H
int myFunction();
#endif /* XYZ_H */

xyz.cpp

#include <iostream>
#include <cmath>
#include "xyz.h"
using namespace std;
int myFunction() {
float a, o1p1, o1p2, o1;
cout << "Input number: "; 
cin >> a;
o1p1 = (1+cos(4*a)); 
o1p2 = (1+cos(2*a)); 
o1 = ((sin(4*a))/o1p1)*((cos(2*a))/o1p2);   
cout << "nZ1 = ";
cout << o1;  
cout << "n "; 
return 0;
}

主.cpp

#include <iostream>
#include "xyz.h"
using namespace std;
int main(int argc, const char * argv[]) {
int cl;
cout << ("Make ur choice (1-1)");
cin >> cl;
switch(cl){
case (1):{
int returnedValue = myFunction();
cout << returnedValue << endl;
}
}
return 0;
}

输出:

Georgioss-MBP:Desktop gsamaras$ g++ main.cpp xyz.cpp -lm
Georgioss-MBP:Desktop gsamaras$ ./a.out 
Make ur choice (1-1)1
Input number: 2
Z1 = -2.18504
0