包含并运行来自其他文件的函数
Include and run function from other file
我有 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
相关文章:
- C++ gmock - 我们如何在单元测试 cpp 文件中读取/获取 cpp 文件函数的参数值
- 使用其他头文件函数的头文件
- 创建文件函数是否可以打开仅在WinObj实用程序中的全局目录下列出的设备的句柄?
- 如何指定创建文件函数获取未缓存的结果?
- 标准库头文件函数原型的实现是如何用 c++ 编写的?
- 如何将类对象作为对另一个头文件函数的引用传递
- 读取文件函数lpbuffer和字节以读取澄清
- C++ - 未定义的对多个文件函数的引用
- 使用C++的可视 Unicode 文件函数
- C 创建文件函数错误
- WinAPI 创建文件函数 2.
- 具有CREATE_ALWAYS处置的创建文件函数
- 重写c库文件函数
- 如何使用客户端调用堆栈中的地址从 PDB 检索文件/函数/行号?
- 通过头文件函数将遍历的数据从二进制搜索树加载到Vector中
- 需要帮助无法弄清楚为什么我的头文件函数声明不起作用
- 是否可以在不使用文件函数的情况下使用代码块从文件运行某些用例测试?
- 如何用c++文件函数读写8位整数单位形式的数据
- 在c++中读文件函数如何识别文本文件的结束
- 使用Windows API的c++文件函数