Using multiple .cpp files in c++ program?

前端 未结 4 2090
时光说笑
时光说笑 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 
    #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.

提交回复
热议问题