C++ includes and Makefiles
I have a two fold question about working with C++ headers and makefiles. I know that I have all the parts, I am just not sure how to put them together.
I have the following files:
main.cpp
Point.cpp
Point.h
Point.h d开发者_JAVA技巧eclares my simple Point object, the definition is inside the Point.cpp file. Then inside of main()
I want to create and use the Point object.
Do I need to include the Point.h file inside of the Point.cpp file or is that something that the Makefile takes care off? Also, the main.cpp file that is using the Point object: do I need an include for Point.cpp or is that something that is done/can be done in the Makefile?
What should each file here include and what should my Makefile look like?
//Working from Linux platform exclusive//
Makefiles are nothing more than a way to run certain commands when certain files are out of date. The make
program knows next to nothing about C++.
You should #include "Point.h"
in both main.cpp and Point.cpp. If you want to make sure that make
rebuilds your program correctly when you edit files, you should explicitly declare main.o and Point.o as dependencies of Point.h.
Here's a fairly simple example:
all : point_app
point_app : Point.o main.o
$(LINK.cc) $^ $(LOADLIBES) $(LDLIBS) -o $@
Point.o : Point.h
main.o : Point.h
gcc/g++ and make have tricks that enable you to automatically generate these header file dependencies, but it's been far too long since I've used them for me to offer proper advise on their use. You could look up the documentation for gcc's -M...
family of options as a starting point.
Makefiles does nothing with your headers. You need to include in your main manually in order to use point.
The header file provides the class definition, therefore wherever you want to use objects of a class, you need to provide it's definition (by including appropriate header file).
The source (cpp) file doesn't have to be included, unless you need the class implementation. That needs to be done for a template class, unless the class is explicitly instantiated.
Makefiles define rules to build libraries or programs, and doesn't include header files.
精彩评论