简体   繁体   中英

how to run c++ file if header, class, and main are not in the same folder?

The code::block IDE generates the following files:

  • ./main.cpp
  • ./include/class.h
  • ./src/class.cpp It include class.h with #include "class.h"

How can I run this set of files, with the three files in three different folders?

  • First, this program can be run by clicking IDE "build and run" button.
  • This program need to take some arguments, like ./a.out arg[1] arg[2] . So I cannot input arguments by clicking "build and run" button, and thus I have to use g++ to compile an output first.
  • But g++ is not smart enough as the IDE in finding the three files(I try g++ -I./include main.cpp , it seems that it has no problem with class.h file, but cannot find class.cpp file)

So how can I compile the three files in three different locations?

BTW, how could the class.h file find the class.cpp file in IDE/g++(scan all the files in the directory to see which contains the definition of the class functions?)?

It's a bad idea to #include source files. But this will do it:

g++ -I./include -Isrc main.cpp

Normally one would expect that the IDE has some function to just build the application, especially when there's a function to build-and-run. In addition there are those that have the possibility to supply command line arguments for the program so build-and-run will run with supplied arguments.

You have to supply the source files and the search path for includes, normally one would write:

g++ -o exec-file-name -I./include main.cpp src/class.cpp

but that may depend a bit on how you include the header file. Another note is that you normally don't compile the header file separately - it's included when you compile the .cpp files that includes it.

If on the other hand you actually want to do what you write (compile the .h file that includes the .cpp file - which is higly unorthodox) you would do:

g++ -c -I./src include/class.h
g++ -c main.cpp
g++ -o exec-file-name main.o class.o 

where you need to replace the .o extension if your platform uses another extension. Note that in this case you should probably not include class.h from main.cpp since that could lead to duplicate symbols.

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