.cpp can not be included in .h file

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//box.cpp
#include"box.h"

box::box(double a, double b, double c)
{
    w=a;
    l=b;
    h=c;
}


box box::operator+(box a)
{
    box s;
    s.w=w+a.w;
    s.l=l+a.l;
    s.h=h+a.h;

    return s;
}
/////////////////////////////////////////////////////////////
//box.h
#ifndef BOX_H_INCLUDED
#define BOX_H_INCLUDED

#include<iostream>

class box
{
    private:

    double w;
    double h;
    double l;

    public:

    box(){std::cout<<"created";};
    box(double a,double b,double c);

    int get_w(){return w;};

    int get_h(){return h;};

    int get_l(){return l;};

    int volum(){return (w*l*h);};

    ~box(){};

    box operator+(box a);




};

#endif // BOX_H_INCLUDED
////////////////////////////////////////////////////////
//main.cpp
#include<iostream>
#include "box.h"

int main()
{


    box a(1,2,3);
    box b(3,2,1);

    box c=a+b;
    std::cout<<c.get_w()<<std::endl;
    std::cout<<c.get_l()<<std::endl;
    std::cout<<c.get_h()<<std::endl;

    return 0;
}




I don't know where is wrong. The error says /mnt/nfs/netapp2/grad/zzhao2/main.o||In function `main':|
main.cpp|| undefined reference to `box::box(double, double, double)'|
main.cpp|| undefined reference to `box::box(double, double, double)'|
main.cpp|| undefined reference to `box::operator+(box)'|
||=== Build finished: 3 errors, 0 warnings ===|

Could any one help me? Thanks! If I write #include"box.cpp" in the main.cpp. it works.
are you sure you are trying to compile and link both files?

 
> g++ main.cpp box.cpp



If I write #include"box.cpp" in the main.cpp. it works.

In this case you are simply textually include box.cpp into main.cpp which is wrong (since if you include box.h into other files, all will receive a copy of box.cpp and there will be collision of names).

read something about compilation sources to object files and linking them together.
Thanks very much. I use the makefile and it compiles sucessfully. But in the ide I used,it does not work.
Topic archived. No new replies allowed.