I want to create a class say PEN in one one c++ file and inherit it in another class that is in a separate file and finally run the program from a C++ file that has only the main function. I know this is a basic thing but I am new to C++. The program is a console program.
-
Hi! What have you tried so far? How are you intending to build the project? Are you for example using CMake or Visualstudio? – user35915 Feb 08 '20 at 11:58
1 Answers
There's a few things here.
. Referencing . Compling . Linking
Referencing You put your classes and main function in separate .cpp files. Each file that references a class in another file needs to #include class.h where class.h is the headers that include the class declarations. You can have a single shared header for all the files, or a separate one for each. Usually there is a .h for each .cpp with the same name by convention.
Compiling Then when you complie, you need to decide if you want a single binary blob (for you, this is my recommendation) or a library to link to. Not sure exactly the cpp compile options but it will be something like: path/to/cpp-compiler main.cpp class.cpp Order is important here, the classes main.cpp needs must be specified AFTER main.cpp on the command line.
Linking If you chose to compile a separate library, you will need to do: path/to/cpp-compiler -c class.cpp path/to/cpp-compiler -c main.cpp separately, then do: path/to/cpp-compiler -o a.out main.cpp class.o to link. You can also pack multiple .o files into a .so or dll if you like and link to that. Linking can become quite complex and has many quirks so I think stick with compiling all you sources together for now until you get more familiar with it.
This is a good answer here: Using G++ to compile multiple .cpp and .h files
I suggest you do a little more research as there are bound to be heaps of other answers to this question.

- 532
- 2
- 12