Why create an include/ directory in C and C++ projects?

前端 未结 3 1058
挽巷
挽巷 2021-02-01 14:22

When I work on my personal C and C++ projects I usually put file.h and file.cpp in the same directory and then file.cpp can reference

3条回答
  •  清酒与你
    2021-02-01 14:29

    1 . .hpp and .cpp doesn't necessary have 1 to 1 relationship, there may have multiple .cpp using same .hpp according to different conditions (eg:different environments), for example: a multi-platform library, imagine there is a class to get the version of the app, and the header is like that:

    Utilities.h

    #include 
    class Utilities{
        static std::string getAppVersion();
    }
    

    main.cpp

    #include Utilities.h
    int main(){
        std::cout << Utilities::getAppVersion() << std::ends;
        return 0;
    }
    

    there may have one .cpp for each platform, and the .cpp may be placed at different locations so that they are easily be selected by the corresponding platform, eg:

    .cpp for iOS (path:DemoProject/ios/Utilities.cpp):

    #include "Utilities.h"
    std::string Utilities::getAppVersion(){
        //some objective C code
    }
    

    .cpp for Android (path:DemoProject/android/Utilities.cpp):

    #include "Utilities.h"
    std::string Utilities::getAppVersion(){
        //some jni code
    }
    

    and of course 2 .cpp would not be used at the same time normally.


    2.

    #include "file.h" 
    

    instead of

    #include "include/file.h" 
    

    allows you to keep the source code unchanged when your headers are not placed in the "include" folder anymore.

提交回复
热议问题