multiple source files

Hi, I've been seeing people declare a class in a .h file, then define it inside a .cpp file. I thought that seemed like good style so I tried to so it as well but just couldn't get it to work. Here's an example of my problem:

main.cpp
1
2
3
4
5
6
#include <iostream>

int main() {
    f.x(2, 5);
    return 0;
}


f.h
1
2
3
4
5
6
7
#ifndef F_H
#define F_H
class F {
public:
    void x(int, int);
} f;
#endif // F_H 


d.h
1
2
3
4
5
6
7
#ifndef D_H
#define D_H
class D {
public:
    void test(bool);
} d;
#endif // D_H 


f.cpp
1
2
3
4
5
#include "f.h"

void F::x(int x, int y) {
    d.test(x > y);
}


d.cpp
1
2
3
4
5
6
7
8
#include "d.h"
void D::test(bool x) {
    if (x) {
        std::cout << "yes" << std::endl;
    } else {
        std::cout << "no" << std::endl;
    }
}


Just as a short little example. Obviously, this isn't gonna work. My question is on how to do the #includes here. If I do them both at the top of main.cpp, I get a "d was not declared in this scope in f.cpp". Any other combination I try gives me "multiple definitions of 'class'".

I'm using Code::Blocks compiling with gcc.
Last edited on
closed account (zb0S216C)
The problem with declaring storage within a header file is that it introduces the possibility of multiple-definition errors. I recommend declaring "d" as external to prevent multiple-definition errors. For example:

Header File A:

1
2
3
4
5
6
#if !defined HEADER_A
#define HEADER_A

extern int Integer;

#endif 

Source File A:

1
2
3
#include Header File A

int Integer;

In the implementation of Header A, "extern" basically means that "Integer" is defined elsewhere. It doesn't matter where "Integer" is defined, so long as it's within a source file. So when ever you include a header file multiple times, the compiler knows that all references to "Integer" will be redirected to "Integer" within the source file where it was initially declared.

In conclusion, don't declare any type of storage within header files unless it's static (the storage will become available only to the file in which the storage was declared). If you have to declare a piece of storage within a header file, it should be declared "extern" and the actual declaration should be within a source file somewhere.

Wazzak
Last edited on
Thanks, Framework!
Topic archived. No new replies allowed.