Lecture 8
make
make
builds main
what does main depend on?
recursively build dependencies - if necessary
then build main - if necessary
How does make decide it is necessary?
checks timestamps (eg.
ls -l
)if target is older than its dependencies (based on last modified time), it is rebuilt
eg.
vec.cc
changesit is newer than
vec.o
rebuild
vec.o
newer than main (executable)
rebuild main
make clean
make clean
full rebuild
Generalize with variables
This file is in repository (example3 Makefile):
main.o: main.cc vec.h
vec.o: vec.cc vec.h
Biggest problem with writing makefiles
writing dependencies and keeping them up to date
can ge help from g++:
g++ -MMD -c vec.cc
creates vec.o and vec.d
Vec.d: vec.o: vec.cc vec.h
Now just include this in the Makefile
To get this file, edit Makefile in repository
What if we want a module to provide a global variable?
Wrong way to do it:
Every file that includes abc.h defines a separate globalNum - program will not link
Solution: put variable in .cc
file
Suppose we write a linear algebra module - code found in separate/example3
Does not compile because
#include "vec.h"
is included twice inmain.cc
, and struct vec cannot be defined twiceNeed to prevent files from being included more than once
Solution: #include guard
First time vec.h is included - symbol VEC_H is not defined, so file is included
Subsequently, VEC_H is defined, so contents of vec.h are suppressed
Always
put
#include guards
in .h files
Never
put
using namespace std;
in .h filesthe usage directive will be forced upon any client that includes the file
always say
std::cin, std::string, etc.
in headers
compile .h files (these are compiled by being included .cc files)
Classes
Can put functions inside of structs eg.
Class: structure type that can have functions Object: an instance of a class Member function/Method: function inside class (eg. grade() in Student) Scope resolution operator: ::
eg. C::f means f is in the context of the class (or namespace) C. :: like ., where LHS is a class (or namespace), not an object
What do assns, mt, final mean inside of Student::grade
?
Key are the fields of the current object - the object upon which grade was called
Difference between method and function
Methods take a hidden extra parameter:
this
a pointer to the object on which the method was called
Can write:
Initializing Objects
Better way:
write a method that initializes: Constructor
Last updated