我如何在多个文件中使用函数,c ++
How i can use functions in multiple files, c++
我在使用多个文件时遇到了一点问题。我有一个任务使用三个文件:function.h,function.cpp,prog.cpp。
在 function.h 中,我定义了每个函数。
在函数中.cpp我输入了每个函数的代码。
在 prog 中.cpp我必须调用函数。在那里我没有定义任何东西。
我有这些错误:
"void __cdecl randInt(int *,int)" (?randInt@@YAXPAHH@Z) already defined in function.obj
"void __cdecl showInt(int *,int)" (?showInt@@YAXPAHH@Z) already defined in function.obj
One or more multiply defined symbols found
功能.cpp:
#include <iostream>
using namespace std;
void randInt(int *arr, int size) {
for (int *i = arr; i < arr + size; i++) {
*i = rand() % 10;
}
}
void showInt(int *arr, int size) {
cout << "Int Massive" << endl;
for (int *i = arr; i < arr + size; i++) {
cout << *i << ", ";
}
cout << endl;
}
函数.h:
#pragma once
void randInt(int *, int);
void showInt(int *, int);
进度.cpp:
#include <iostream>
#include <ctime>;
using namespace std;
#include "function.h"
#include "function.cpp"
int main()
{
srand(time(0));
int n = 10;
int *arrInt = new int[10];
randInt(&arrInt[0], n);
showInt(&arrInt[0], n);
return 0;
}
包含
.cpp文件是不正确的和不必要的,所以删除#include "function.cpp"
你应该没问题。
您应该以这种方式编辑文件
函数.h
#pragma once
void randInt(int *, int);
void showInt(int *, int);
功能.cpp
#include <iostream>
#include "function.h"
using namespace std;
void randInt(int *arr, int size) {
for (int *i = arr; i < arr + size; i++) {
*i = rand() % 10;
}
}
void showInt(int *arr, int size) {
cout << "Int Massive" << endl;
for (int *i = arr; i < arr + size; i++) {
cout << *i << ", ";
}
cout << endl;
}
PRG.cpp
#include <iostream>
#include <ctime>;
#include "function.h"
using namespace std;
int main()
{
srand(time(0));
int n = 10;
int *arrInt = new int[10];
randInt(&arrInt[0], n);
showInt(&arrInt[0], n);
return 0;
}
然后,您可以通过将 prg.cpp 与函数.cpp文件链接来编译程序。如果您使用的是 g++ 编译器,则可以按照下面给出的方式执行此操作。
g++ prg.cpp fuction.cpp
相关文章:
- 用C++在单独的头文件中完成函数体
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 头文件、宏和内联函数c++
- 如何使用单独文件中的派生类访问友元函数对象
- C++无法定义虚拟函数 OUTER 类和头文件
- 回溯C++不打印函数,因此文件
- 如何从另一个文件继承私有成员变量和公共函数
- 从函数角度看ID到文件路径的内部与外部映射
- 区分非成员函数和头文件中的成员函数
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 如何在其他文件中使用函数
- 整数键映射到头文件中的成员函数指针
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 用"=default"声明的函数应该只在头文件中执行
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- C++ - 在一个函数/文件中初始化变量然后在main()/另一个文件中使用它的最佳方法是什么?
- C++单独的函数文件
- 只对单个函数/文件启用编译器优化