Cox
Cox

Reputation: 35

C++ Visual Studio 2010 LNK2019 Error - Some basic advice is needed

I got the following code:

FooClass.h

#pragma once

#include <string>
#include "StdAfx.h"
#include "FooClass.h"

#include <iostream>
#include "FooClass.h"

FooClass::FooClass(void)
{
}


FooClass::~FooClass(void)
{
}


int PrintMsg (std::string msg)
{
    printf ("%s\n", msg);
    return 1;
}

class FooClass
{
public:
    FooClass(void);
    ~FooClass(void);

    static int PrintMsg (std::string msg);
};

FooClass.cpp


CODETESTER.cpp

// CODETESTER.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include "FooClass.h"

int _tmain(int argc, _TCHAR* argv[])
{
    FooClass::PrintMsg ("Hi World!!");

    return 0;
}

When bulding the project I´m getting the following error:

Erro 4 error LNK2019: símbolo externo indefinido "public: static int __cdecl FooClass::PrintMsg(class std::basic_string,class std::allocator >)" (?PrintMsg@FooClass@@SAHV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenciado na função _wmain E:\2. MEZASOFT\DESENVOLVIMENTO\PROTOTIPOS\CODETESTER\CODETESTER\CODETESTER.obj CODETESTER

I´ve read several articles regarding this theme, as well as help, but did not found out how to FIX it.

I know that the .h is not enough to let linker know where the PrintMsg code is, but - how can I solve it.

Sorry if this is a basic question. I used to be a good C programmer a long time ago. I´m coming back as a C++ programmer.

Upvotes: 1

Views: 1074

Answers (1)

helloworld922
helloworld922

Reputation: 10939

You declared the PrintMsg function for FooClass, but you never defined/implemented it. Instead, you defined a function PrintMsg which really isn't associated with the FooClass.

To properly implement the PrintMsg function for FooClass:

int FooClass::printMsg(std::string msg)
{
    printf("%s\n", msg.c_str());
    return 1;
}

As a side note, you probably should pass the parameter msg by reference. This way the string object isn't being copied each time printMsg gets called.

// you'll also need to change the printMsg declaration inside the FooClass
int FooClass::printMsg(const std::string &msg)
{
    printf("%s\n", msg.c_str());
    return 1;
}

Upvotes: 2

Related Questions