Modular programming

B

bob

I have made a file: box.h that have some structs, simple functions
etc.

I have then made another file: print.h that have a class 'print' with
methods to print the content from 'box' (content of various structs,
fields etc) which currently does not work.

in box.h I write:

#include "print.h"

And then I make a new print object like 'Print p' and it works fine
when I from 'box.h' do something like:

p.printLine()

But how do I make 'print.h' aware of the types and struct in box.h?

In box.h I have the struct 'Line'. I would like to pass this struct to
a Print object like:

Line test;
p.printLine2(test);


Therefore I have in print.h written:

#include "box.h"

but when I define the function in print.h:

void printLine2(Line a) {
std::cout << "test\n";
}

I just get:

error: 'Line' has not been declared


Why can I use print.h in box.h but not make print.h aware of the types
in box.h?
 
A

Adam Nielsen

in box.h I write:
#include "print.h"
Therefore I have in print.h written:

#include "box.h"

There's your problem - every time the compiler reads in one .h file,
you're telling it to look in the other one. Your compiler is obviously
smart enough to realise the problem, but the side effect is that your
function definition is being read before the definition of Line.

The real issue of course is that you're putting code into the .h files.
The .h files are only meant for definitions. If you put code into .h
files you're not actually writing modular programs, as after all the
#include directives have been processed you will only have one really
big module.

What you need to do is to split the code into multiple .cpp files, as
each .cpp file is normally treated as one module, regardless of how many
..h files it includes.

There should be plenty of tutorials on the web explaining how to do this
in more detail.

Cheers,
Adam.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,787
Messages
2,569,629
Members
45,330
Latest member
AlvaStingl

Latest Threads

Top