简体   繁体   中英

How do I compile and link multiple files from the command line?

I used to use visual studio as a compiler for C++. I have been recently using g++ in cygwin. My problem is I donot know how to use cygwin for inheritance. The code below is just for illustration, to make my question more clearer.

Base class:

// A.h:
class A{
void func1();
};
class B:A{
func2();
};

//-------------
//A.cpp:
#include"A.h";
A::func1(){
};
//-----------

//B.cpp:
#include"A.h";
B::func2(){
func1();
};

int main(){
B b.
b.func2();
return 0;}
//----------------

I run (similar to ) this without any problem in visual studio. But I do not know how to run it in cygwin. How to include Ah , A.cpp, to run main() in B.cpp.

You need to compile your class implementation files into object files first, then link them.

If you were to use the g++ compiler , you could run these commands...

  1. g++ -c A.cpp
  2. g++ -c B.cpp
  3. g++ Ao Bo main.cpp -o my_program

This can be automated with a Makefile , so you don't have to type everything out. As others have mentioned GDB can also be used for debugging, but you need to add the '-g' option to your compiler flags to created debugging symbols.

Also, you have a period at the end of line 1 of your main function, rather than a semi-colon.

Learn about makefiles... or type this in command line

g++ -Wall -c -g -o A.o A.cpp
g++ -Wall -c -g -o B.o B.cpp
g++ -o myProgram.exe A.o B.o

You need to compile both cpp files to object files, then link them together. I expect you use g++ and it's in PATH.

Note:

  • I used -g to generate "debug" files
  • I used -Wall to show all warnings (golden rule : fix warnings)

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