Force one include file to be included before another

Imagine I have two files .hpp:

#ifndef _DEF_FILE_1_
#define _DEF_FILE_1_
inline void some_function_1(){
    /*do stuff*/
}
#endif

and

#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_
#ifdef _DEF_FILE_1_
inline void some_function_2(){
    /*do stuff using some_function_1()*/
}
#else
inline void some_function_2(){
    /*do the same stuff without using some_function_1()*/
}
#endif
#endif

My problem arises when I do not know in what order the files are included, for example: in main.cppI may have something like:

#include "file1.hpp"
#include "file2.hpp"
int main(){
    some_function_2();
    /*will call the function that uses some_function_1()*/
}

or

#include "file2.hpp"
#include "file1.hpp"
int main(){
    some_function_2();
    /*will call the function that doesn't use some_function_1()*/
}

Is there a way to make sure that as soon as file1.hpp, and file2.hpp included, then the some_function_2()cause some_function_1()?

PS: One solution is to include file1.hppin file2.hpp, but I can’t do that, because I am developing code that may or may not depend on some library that the end user may or may not have.

PPS: , ( , ) "" some_method_2(), file1.hpp , file2.hpp.

+2
4

, some_function_2() SFINAE . , cpp, , some_function_1(), .

+1

, " " - , . , - :

2.hpp

#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_
#ifdef _DEF_HAS_SOME_LIBRARY_
#include "file1.hpp"
inline void some_function_2(){
    /*do stuff using some_function_1()*/
}
#else
inline void some_function_2(){
    /*do the same stuff without using some_function_1()*/
}
#endif
#endif

, , file1.hpp some_function_1() #include "file1.hpp" .

main.cpp 2.hpp.

// optionally #define _DEF_HAS_SOME_LIBRARY_
#include "file2.hpp"
int main(){
    some_function_2();
    /*will call the function that uses some_function_1()*/
}

, , , .

0

, , c ++. , .

. . / script configure.h . . ​​ #define FILE1_HPP_EXISTS 1.

configure.h, .

0

, _has_include:

file2.hpp :

#ifndef _DEF_FILE_2_
#define _DEF_FILE_2_

#if defined(__has_include) && __has_include("file1.hpp")
# include "file1.hpp"
inline void some_function_2() {
    /*do stuff using some_function_1()*/
}
#else
inline void some_function_2() {
    /*do the same stuff without using some_function_1()*/
}
#endif
#endif

, .

0

Source: https://habr.com/ru/post/1607824/


All Articles