Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ makefile on Linux with Multiple *.cpp files

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.

like image 888
NewFile Avatar asked Oct 02 '13 16:10

NewFile


People also ask

What is C in Makefile?

c file contains the main function, the server. c file contains the user defined function, The third file which is server. h header file which calls the user defined functions in the server. c file and the fourth file which is makefile.mk which contains set of all the commands with their variable names.

How do I add a header file in Makefile?

The only way to include the header file is to treat the filename in the same way you treat a string. Makefiles are a UNIX thing, not a programming language thing Makefiles contain UNIX commands and will run them in a specified sequence.

What are the advantages of Makefile in Linux?

Advantages: It makes codes more concise and clear to read and debug. No need to compile entire program every time whenever you make a change to a functionality or a class. Makefile will automatically compile only those files where change has occurred.


2 Answers

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 :)

like image 113
torpedro Avatar answered Oct 17 '22 06:10

torpedro


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
like image 25
Brian Cain Avatar answered Oct 17 '22 06:10

Brian Cain