Using .h and .cpp files in an online C++ compiler (and why most of them fail)
Most online C++ compilers give you one editor, and one editor means one file. That's fine until your course splits a class into Student.h and Student.cpp . Then the second line of main.cpp stops the build: code.cc:2:10: fatal error: Student.h: No such file or directory 2 | #include "Student.h" | ^~~~~~~~~~~ compilation terminated. Here's why that happens, three ways around it, and the linker…
Most online C++ compilers present you with a single editor and a single file. This works fine until your instructor divides a class into separate .h and .cpp files, such as Student.h and Student.cpp. When you attempt to compile the code on such an online platform, you encounter a fatal error like this: code.cc:2:10: fatal error: Student.h: No such file or directory.
The reason behind this issue is that the online compiler treats your code as if it is in a single folder containing just one file. Consequently, the compiler cannot locate the Student.h header file.
There are three ways to overcome this limitation:
1. Pasting the header file: You can directly insert the entire Student.h header into your main.cpp file. However, this approach is not recommended for larger projects, as it defeats the purpose of using separate header and source files for organization and modularity.
2. Utilizing an online Integrated Development Environment (IDE) with project support: Platforms like OnlineGDB, Playcode, and Replit allow you to create projects, where you can add multiple .cpp and .h files. These tools enable you to compile and run each file individually, providing a more structured environment for learning and testing your code.
3. Sending the files to a compiler API: If you are integrating the compiler with a script, course platform, or autograder, you can send the individual files as part of the program. Services like OnlineCompiler.io provide an API that accepts your main.cpp file along with other source files in a files list. By sending the files with the program, the compiler processes them together, linking and compiling them as required.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.