简体   繁体   中英

implement recursive function that avoid infinite loop input caused by a circular call of include (no with #pragma once) in c++

Suppose I have function that load all the includes in certain file.I need to write function in c++ that load all the includes in some given source file so I will avoid infinite loop and circular call for the include.

To solve the question I have to use this function i can't use pragma once or something similar I think it could be solved by recursion though I am not sure how

Usually the compiler will tell you if a file directly or indirectly includes itself, eg by an error message like #include nested too deeply . To test this for a particular file, let's say a myprogram.cpp , you could use the "preprocessor only" option -E of the g++ compiler:

g++ -E myprogram.cpp

It will resolve all the macros and #includes, and it will tell you if there is such a recursion you described.

If it is, however, a homework or just for your practice, note that an #include might be surrounded by other preprocessor directives like #ifdef ... which influence the actual inclusions.

If you are allowed to ignore such #ifdef -things, you could...

  1. write a function that takes a filename as parameter and reads all the lines of a file

  2. that maintains a stack of filenames and pushes the filename parameter to this stack once the function (1) is called.

  3. if a line contains an #include , checks if the file to be included is already in the stack of (2). If yes, you've detected an (endless) recursion. Otherwise, call the function (1) recursively with that filename.

  4. take the filename from the stack once a run of (1) has finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM