使用另一个 cpp 文件的函数

using functions of another cpp file

本文关键字:函数 文件 cpp 另一个      更新时间:2023-10-16

我有一个包含以下内容的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