1

I am trying to run a function from a class file, but it is not working and I get the the following error messages: error LNK1120: 1 unresolved externals

error LNK2019: unresolved external symbol "public: void __thiscall NS::Class1::test(void)" (?test@Class1@NS@@QAEXXZ) referenced in function _main

//Main.cpp

#include<iostream>
#include<string>
#include<Windows.h>
#include "Class1.h"

int main(){
    NS::Class1 E;
    E.test();
    return 0;
};


//Class1.cpp

#include <Windows.h>
#include <string>
namespace NS{
class Class1{
        Class1(){
            OutputDebugString(L"Created.");
        }

        void test(){
            OutputDebugString(L"Hello World");
        }
    };
}


//Class1.h

#ifndef _Class1_H_
#define _Class1_H_
namespace NS{
    class Class1{
        public:
            void test();
        };
}
#endif

3 Answers3

6

In your source file, you're redefining the class, rather than defining its member functions. That will give undefined behaviour, since you're only allowed to define the class once. The source file should look more like:

#include "Class1.h"
#include <Windows.h>

NS::Class1::Class1(){
    OutputDebugString(L"Created.");
}

void NS::Class1::test(){
    OutputDebugString(L"Hello World");
}

You'll also need to modify the class definition in the header, since it doesn't declare a constructor.

Also, make sure that your project is compiling and linking both source files.

Cameron
  • 96,106
  • 25
  • 196
  • 225
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

Your header file contains reserved IDs for the include guard and misses the declaration of the constructor. It should look like this:

#ifndef CLASS1_H
#define CLASS1_H

namespace NS {

class Class1
{
public:
    Class1();
    void test();
};

}
#endif

The definition of the class should not include the class declaration, it should include it, and should look more like this:

#include <Windows.h>

#include "Class1.h"

namespace NS {

Class1::Class1()
{
    OutputDebugString(L"Created.");
}

void Class1::test()
{
    OutputDebugString(L"Hello World");
}

}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
0

I think your .cpp file might be causing the issue. Since you already created the class definition in your header with class member declarations, just import the Class1.h header in the Class1.cpp file and scope the member functions then defining their behavior.

so maybe try:

#include <Class1.h>

NS::Class1::Class1(){}//constructor

void NS::Class1::test(std::cout << "hi"){}
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
ak_2050
  • 159
  • 4
  • #include what exactly? Can you sort out the format of your answer? – doctorlove Oct 10 '13 at 16:09
  • sorry, i meant #include "Class1.h" as the checked answer above stated. The checked answer is very good and correct. More elaborate than mine :) – ak_2050 Oct 10 '13 at 16:16