views:

195

answers:

3

I'm playing around with Box2D for fun right now, and after getting the hang of some of the concepts I decided to make my own test for the test bed (Box2D comes with a set of examples and has a simple extendable Test class for making your own tests). I started by grabbing one of the other tests, ripping out everything but the function signatures, and inserting some of my own code.

However, there's no #includes to any of Box2D's libraries so it doesn't compile (but only my file errors, remove my test file and it compiles fine). I figured I must have accidentally deleted them when I was moving stuff around, but upon checking the other test files there's no #includes anywhere to be seen. Each one of the files uses datastructures and functions that are declared in various Box2D header files. How does this compile at all?

For example, this is one of the prepackaged tests stripped of the constructor body and some comments at the top:

#ifndef CHAIN_H
#define CHAIN_H

class Chain : public Test
{
public:
    Chain()
    {
  // Since b2BodyDef isn't defined in this file, and no 
  // other files are included how does this even compile?
  b2BodyDef bd; 


  // rest of constructor...
    }

    static Test* Create()
    {
     return new Chain;
    }
};
#endif
+2  A: 

Perhaps the the header that does define b2BodyDef is #included in the .cpp before this header? There are obviously other headers involved, or you would not be able to refer to class Test.

anon
+2  A: 

The #ifndef CHAIN_H at the beginning is a common pattern that indicates to me that this is from a file called chain.h.

Header files like the chain.h you're quoting are not intended to be stand-alone compilable. Most likely you need to create a simple C++-file which includes this and the necessary other files before it:

test.cpp:

#include "box2d.h"
#include "chain.h"

// more code here.
David Schmitt
+1  A: 

Each cpp file gets compiled. Before it is compiled though, the preprocessor runs. The preprocesser deals with all of the keywords starting with #, like #include. The preprocessor takes the text of any #include'd files and replaces the #include statement with all the text in the file it includes. If the #include'd file includes other files, their text is fetched too.

After the preprocessor has run, you end up with a great big text file called a translation unit. This is what gets compiled.

So.. probably as other people have said. The cpp file somewhere includes the Box2D stuff before it includes chain.h, so everything works. There is often an option on the compiler or the project settings that will get the preprocessor to create a file with all of the text in the translation unit so you can see it. This is sometimes useful to track down errors with #includes or macros.

Scott Langham