使用另一个 cpp 文件的函数
using functions of another cpp file
我有一个包含以下内容的main.cpp
文件:
#include<iostream>
using namespace std;
#include"Command.cpp"
#define EXIT 5
int main(){
int code;
do{
code = getCommand();
doCommand(code);
}while(code != EXIT);
}
在我的Command.cpp
文件中,我有一些功能:
#include<iostream>
using namespace std;
#include"Service.h"
Service * first = new Service();
int getCommand(){
cout<<"Choose one of the following commands: "<<endl;
cout<<"1. Add new service"<<endl;
cout<<"2. Add new subservice"<<endl;
cout<<"3. Add parent to a service"<<endl;
cout<<"4. Delete a service(and it's subservices)"<<endl;
cout<<"Your Choice: ";
int c;
cin>>c;
return c;
}
void addService(){
first->add();
}
void addSubService(){
cout<<"Let's choose the parent first: "<<endl;
int * one = new int;
*one = 1;
first->print(one,0);
cout<<"0. here."<<endl<<"> ";
int id;
cin>>id;
Service * f = first->find(one,id);
}
void addParentToService(){
}
void doCommand(int c){
switch(c){
case 1:
addService();
break;
case 2:
addSubService();
break;
case 3:
addParentToService();
break;
case 4:
//deleteService();
break;
}
}
但是当我在Visual Studio中点击编译按钮时,我收到以下错误:
1>Command.obj : error LNK2005: "void __cdecl addParentToService(void)" (?addParentToService@@YAXXZ) already defined in Source.obj
1>Command.obj : error LNK2005: "void __cdecl addService(void)" (?addService@@YAXXZ) already defined in Source.obj
1>Command.obj : error LNK2005: "void __cdecl addSubService(void)" (?addSubService@@YAXXZ) already defined in Source.obj
...
我相信问题出在这些文件的链接上,但我不知道该怎么办......
切勿将 cpp 文件包含在其他 cpp 文件中。这就是使用 .h 文件的地方。您可以参考这个关于如何做到这一点的SO问题:
在 c++ 程序中使用多个.cpp文件?
从本质上讲,您遇到的问题是多次包含 Command.cpp 文件。预处理器获取文件的内容,并将其直接复制到它所包含的文件中,这意味着如果您的文件没有被重新包含,您最终可能会对同一对象进行多个定义。(这也是包括警卫发挥作用的地方)。
这是一个总体上的大主题,并且有许多资源可以讨论此内容。
如果要跨不同文件链接函数,切勿将.cpp
文件包含在另一个.cpp
文件中。您只包括.hh
文件,您可以在其中定义任何其他函数,这些函数跨其他.cpp
文件实现。
示例:main.cpp
#include "42.hh"
#include <iostream>
int main() {
func42();
return 0;
}
包含文件:42.hh
#ifndef _42_HH_
#define _42_HH_
void func42();
#endif
功能文件:42.cpp
#include <iostream>
void func42() {
std::cout << "Fourty-two" << std::endl;
}
编译并运行:
~$ g++ 42.cpp main.cpp -o fourty-two
~$ ./fourty-two
Fourty-two
相关文章:
- 用C++在单独的头文件中完成函数体
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 头文件、宏和内联函数c++
- 如何使用单独文件中的派生类访问友元函数对象
- C++无法定义虚拟函数 OUTER 类和头文件
- 回溯C++不打印函数,因此文件
- 如何从另一个文件继承私有成员变量和公共函数
- 从函数角度看ID到文件路径的内部与外部映射
- 区分非成员函数和头文件中的成员函数
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 如何在其他文件中使用函数
- 整数键映射到头文件中的成员函数指针
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 用"=default"声明的函数应该只在头文件中执行
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- C++ - 在一个函数/文件中初始化变量然后在main()/另一个文件中使用它的最佳方法是什么?
- C++单独的函数文件
- 只对单个函数/文件启用编译器优化