1

I began to write my program in a single cpp-file but now I have too much code so I decided to separate it. But the problem is that I have many constants, includes and some other things that I want to have all in one place. Unfortunately, all of them are needed by dependent parts of code so I can't do it with usual include files.

What would help me?

(I write under Linux and compile with command-line)

(Sorry for my English :))

user1431314
  • 123
  • 1
  • 5
  • I think the answer to this question http://stackoverflow.com/questions/346058/c-class-header-files-organization provides what you're looking for. – kenrogers Jun 01 '12 at 19:59

2 Answers2

2

As Hristo said, you should generally write the definitions in header files and write the implementation in the source code files.

To answer your question however:

But the problem is that I have many constants, includes and some other things that I want to have all in one place.

What I've typically done is create a single file called something like "common.h" or "defs.h" (I took the idea from Doom...) and that file has many defines that you find you need throughout your entire program. If you are using constants, declare the constants in the header file like so:

    extern const int MAX_SOMETHING;
    extern const bool TRUTH_VALUE;

and make a complementary source file (defs.cpp or common.cpp) that defines these constants:

    const int MAX_SOMETHING = 5;
    const bool TRUTH_VALUE = true;

so now when you include the common/defs.h in other source files, the extern keyword will tell that source file that the definition is in another source file (its in the common/defs.cpp) so it will find the definition in there, and you can use it anywhere where you have included common/defs.cpp.

wardd
  • 562
  • 3
  • 8
1

In most projects definitions are in header files and implementations are in source code files. However the implementations of template functions must be in the header files because they must be visible to all source files using them. Variables should be defined extern in header files and be declared in source files. Constants may also be declared in header files static.

Example:

Foo.h

#pragma once
class Foo{
    public:
        void bar();
        template<class Type>
        void increment(Type &a){
            ++a;
            return;
        }
};
extern Foo theFoo;
static const int five=5;

Foo.cpp

#include "Foo.h"
#include <iostream>
void Foo::bar(){
    std::cout<<"Foo::bar called"<<std::endl;
    return;
}
Foo theFoo;

Main.cpp

#include "Foo.h"
#include <iostream>
int main(){
    theFoo.bar();
    std::cout<<five<<std::endl;
    return 0;
}
Hristo Venev
  • 841
  • 5
  • 16