开发者

#include .h or .cpp file?

开发者 https://www.devze.com 2023-04-12 06:07 出处:网络
So I开发者_JS百科 have this weird looking problem: my very basic program generates an error message (undefined reference to \'foo::foo(int)\') when i import the .h file of a separate class. However, w

So I开发者_JS百科 have this weird looking problem: my very basic program generates an error message (undefined reference to 'foo::foo(int)') when i import the .h file of a separate class. However, when I change the import file to .cpp, it all works.

Now, I've read a little, and seen a few video tutorials, and they all say the same: import the .h file. So why doesn't it work?

I use Code::Blocks, where i compile and run(no command lines), in Windows 7. I do suspect that something isn't set up quite right, however, I do want to know for sure if it is my code that fails.

Main.cpp:

#include <iostream>
#include "Foo.h"  //This don't work. If i include Foo.cpp it does. 

using namespace std;

int main()
{
    Foo k(10);
    cout << k.getInt() << endl;
}

foo.h:

#ifndef FOO_H
#define FOO_H

class Foo
{
    public:
        Foo(int tall);
        int getInt()const;
    protected:
    private:
        int m;
};

#endif

Foo.cpp:

#include "Foo.h"

Foo::Foo(int tall)
: m(tall)
{
    //ctor
}

int Foo::getInt()const
{
    return m;
}


You need to compile both main.cpp and foo.cpp and link the 2 resulting object files together.


You are failing to compile and/or link the Foo.cpp file when you do your linking step. I'm not familiar with Code::Blocks though, so I can't tell you how to fix it.


Right-click on your .cpp file and go to properties. On build tab make sure compile, link, debug, and release are checked.

#include .h or .cpp file?

0

精彩评论

暂无评论...
验证码 换一张
取 消