1

I have a hometask in witch I can't use any of include directives before the function I should write. But I can use 2 directives given as string arguments of the function . How can I #include that directives inside of that function?

There is my code and I have no idea how to make it work. (In the final version the main() part would be deleted, because the code is checked by University's program, and it has it's own main())

//START        
void SortCount ( string first, string header1, string header2){        

    #include <header1>        
    #include <header2>    
}

int main(){    

    string hey = " ";    
    SortCount (hey, "iostream", "fstream");         
    return 0;        
}
John Burger
  • 3,662
  • 1
  • 13
  • 23
  • 6
    It's not possible. – tkausl Jan 04 '19 at 18:18
  • 1
    You are mixing what the precompiler does (including header) and what the compiler does. – Matthieu Brucher Jan 04 '19 at 18:18
  • 1
    The preprocessor includes (basically copy/pastes) files _before_ the code actually runs. Since the string is being provided at runtime, there is no way to include a library in this way. – Arnav Borborah Jan 04 '19 at 18:21
  • By the time a function can possibly run (`constexpr` included) all preprocessor directives such as `#include` and `#define` have already been resolved. – François Andrieux Jan 04 '19 at 18:21
  • 3
    It seems to me like you've misunderstood the assignment. But it's not clear what it might actually be asking. – François Andrieux Jan 04 '19 at 18:23
  • Helpful reading on why this is not possible: [How does the compilation/linking process work?](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) – user4581301 Jan 04 '19 at 19:07

1 Answers1

0

C++ is a static language, hence you are not allowed to add headers dynamically.

You can use gcc to include a file to your build without using #include "file.h"

g++ -include file.h main.cpp main.o

See GCC -include