Using multiple .cpp files in c++ program?

前端 未结 4 2074
时光说笑
时光说笑 2020-11-28 04:05

I recently moved from Java for C++ but now when I am writing my application I\'m not interested in writing everything of the code in the main function I want in main functio

相关标签:
4条回答
  • 2020-11-28 04:12

    You can simply place a forward declaration of your second() function in your main.cpp above main(). If your second.cpp has more than one function and you want all of it in main(), put all the forward declarations of your functions in second.cpp into a header file and #include it in main.cpp.

    Like this-

    Second.h:

    void second();
    int third();
    double fourth();
    

    main.cpp:

    #include <iostream>
    #include "second.h"
    int main()
    {
        //.....
        return 0;
    }
    

    second.cpp:

    void second()
    {
        //...
    }
    
    int third()
    { 
        //...
        return foo;
    }
    
    double fourth()
    { 
        //...
        return f;
    }
    

    Note that: it is not necessary to #include "second.h" in second.cpp. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.

    0 讨论(0)
  • 2020-11-28 04:15

    In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h" to your main.cpp file.

    In second.h you just declare like this void yourFunction(); In second.cpp you implement it like

    void yourFunction() { 
       doSomethng(); 
    }
    

    Don't forget to #include "second.h" also in the beginning of second.cpp

    Hope this helps:)

    0 讨论(0)
  • 2020-11-28 04:16

    You must use a tool called a "header". In a header you declare the function that you want to use. Then you include it in both files. A header is a separate file included using the #include directive. Then you may call the other function.

    other.h

    void MyFunc();
    

    main.cpp

    #include "other.h"
    int main() {
        MyFunc();
    }
    

    other.cpp

    #include "other.h"
    #include <iostream>
    void MyFunc() {
        std::cout << "Ohai from another .cpp file!";
        std::cin.get();
    }
    
    0 讨论(0)
  • 2020-11-28 04:18

    You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.

    // main.cpp
    #include "second.h"
    int main () {
        secondFunction();
    }
    
    // second.h
    void secondFunction();
    
    // second.cpp
    #include "second.h"
    void secondFunction() {
       // do stuff
    }
    
    0 讨论(0)
提交回复
热议问题