8

I'm trying to make a makefile with multiple files. Can someone help me? The files I have are file1.cpp, file2.h and main.cpp

file1.cpp contains my functions. file2.h contains the declaration of my functions.

main.cpp [includes file2.h in the code] file1.cpp [includes file2.h in the code]

i did

all: main
gcc -g -Wall -o main main.cpp

but it gives me tons of bugs when i try to compile. my codes works perfectly fine on eclipse.

NewFile
  • 501
  • 5
  • 10
  • 16
  • Best answer is right here. http://stackoverflow.com/questions/3202136/using-g-to-compile-multiple-cpp-and-h-files – user3497443 Sep 15 '16 at 10:53

2 Answers2

10

you'll need to compile all .cpp files that you use (i assume they are not included somewhere). That way the compiler will know that file1.cpp and main.cpp are used together. Also I would suggest using g++ instead of gcc, because g++ is the specific c++ compiler while gcc supports C and C++.

Try using:

g++ -g -Wall -o main main.cpp file1.cpp

Also I would recommend to use Makefile variables like this:

SOURCES = main.cpp file1.cpp
g++ -g -Wall -o main $(SOURCES)

Hope this helps :)

torpedro
  • 494
  • 5
  • 13
1

but it gives me tons of bugs when i try to compile. my codes works perfectly fine on eclipse.

gcc is not a C++ compiler. Use g++ instead.

Your Makefile should look like so, it can leverage implicit rules:

all: main

CXXFLAGS+=-g -Wall
LDLIBS+=-lstdc++
main: file1.o main.o
Brian Cain
  • 14,403
  • 3
  • 50
  • 88
  • 2
    gcc is a C++ compiler. g++ uses gcc, but just in a way that it treats all files as C++ files (including *.c files) – elimirks Oct 02 '13 at 17:13