Académique Documents
Professionnel Documents
Culture Documents
int main() {
float x; Program starts here.
cin >> x; Local variable declaration.
cout << c(x) << endl; Console input.
Console output.
return 0; Exit main function.
}
// This is main.cc // This is mymath.h
#include <iostream> #ifndef MYMATH
#include “mymath.h” #define MYMATH
using namespace std;
float c(float x);
int main() { float d(float x);
// ...stuff...
} #endif
g++ -c main.cc g++ -c mymath.cc g++ -c mydraw.cc
main.o mymath.o mydraw.o
g++ -o myprogram main.o mathstuff.o drawstuff.o
myprogram
// This is main.cc
#include <GL/glut.h> Include OpenGL functions.
#include <iostream> Include standard IO
using namespace std; functions.
Long and tedious
int main() { explanation.
cout << “Hello!” << endl;
glVertex3d(1,2,3);
return 0; Calls function from standard
IO.
}
Calls function from
OpenGL.
Technical reasons.
Only rebuild object files for modified source files.
This is much more efficient for huge programs.
Most assignments include
INCFLAGS = \
-
I/afs/csail/group/graphics/courses/6.837/public/includ
e
LINKFLAGS = \ makefiles, which describe
-L/afs/csail/group/graphics/courses/6.837/public/lib \
-lglut -lvl the files, dependencies, and
steps for compilation.
CFLAGS = -g -Wall -ansi
CC = g++
SRCS = main.cc parse.cc curve.cc surf.cc camera.cc
OBJS = $(SRCS:.cc=.o)
PROG = a1
depend:
makedepend $(INCFLAGS) -Y $(SRCS)
the stuff from the past few
clean:
slides.
rm $(OBJS) $(PROG)
return 0;
}
#include <iostream> Allocate the array during
using namespace std;
runtime using new.
int main() {
int n;
No garbage collection, so
cin >> n;
float *f = new float[n];
you have to delete.
int main() {
float x = 3;
twice2(x); The variable is
cout << x << endl; unchanged.
return 0;
}
vector<float>
twice(vector<float> x) {
int n = x.size(); There is an incredible
for (int i=0; i<n; i++) amount of overhead here.
x[i] = 2*x[i];
return x;
} This copies a huge array
two times. It’s stupid.
int main() {
vector<float>
y(9000000); Maybe the compiler’s
y = twice(y); smart. Maybe not. Why
return 0;
}
risk it?
void twice3(float *x) { Pass pointer by value
(*x) = 2*(*x); and
} access data using
asterisk.
void twice4(float &x) {
x = 2*x;
} Pass by reference.
int main() {
float x = 3;
twice3(&x);
twice4(x);
return 0; Address of variable.
} The answer is 12.
You’ll often see objects passed by reference.
Functions can modify objects without copying.
To avoid copying objects (often const references).