06.08.2013 Views

Laboratory Exercises, C++ Programming

Laboratory Exercises, C++ Programming

Laboratory Exercises, C++ Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4 The GNU Compiler Collection and <strong>C++</strong><br />

• Define the class in a file myclass.h:<br />

#ifndef MYCLASS_H // include guard<br />

#define MYCLASS_H<br />

// #include necessary headers here<br />

class MyClass {<br />

public:<br />

MyClass(int x);<br />

// ...<br />

private:<br />

// ...<br />

};<br />

#endif<br />

• Define the member functions in a file myclass.cc:<br />

#include "myclass.h"<br />

// #include other necessary headers<br />

MyClass::MyClass(int x) { ... }<br />

// ...<br />

• Define the main function in a file test.cc (the file name is arbitrary):<br />

#include "myclass.h"<br />

int main() {<br />

MyClass m(5);<br />

// ...<br />

}<br />

The include guard is necessary to prevent multiple definitions of names. Do not write function<br />

definitions in a header (except for inline functions and template functions).<br />

The g++ command line looks like this:<br />

g++ [options] [-o outfile] infile1 [infile2 ...]<br />

All the files in a program can be compiled and linked with one command (the -o option specifies<br />

the name of the executable file; if this is omitted the executable is named a.out):<br />

g++ -o test test.cc myclass.cc<br />

To execute the program, just enter its name:<br />

./test<br />

However, it is more common that files are compiled separately and then linked:<br />

g++ -c myclass.cc<br />

g++ -c test.cc<br />

g++ -o test test.o myclass.o<br />

The -c option directs the driver to stop before the linking phase and produce an object file, named<br />

as the source file but with the extension .o instead of .cc.<br />

The driver can be interrupted also at other stages, using the -S or -E options. The -S option<br />

stops the driver after assembly code has been generated and produces an assembly code file

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!