I have a test class declared in a header file and defined in a separate file. The class must compile differently under Windows, so i use #if defined ( _WINDOWS_ ). When I compile the cpp file which also contains #if defined ( _WINDOWS_ ), the file is compiled as if the symbol _WINDOWS_ was not defined, although it is defined in another file. When I compile the code, I am getting the following error:
Error Code : error lnk2019 unresolved external symbol public
source code
// test.h
class Test
{
public:
#if defined (_WINDOWS_)
void printwindow();
#endif
void notwindows();
};
//test.cpp
#include "test.h"
#if defined (_WINDOWS_)
void Test::printwindow()
{
cout << "i am windows ";
}
#endif
void test::notwindows()
{
cout << " not windows " ;
}
//main.cpp
#include "windows.h"
#include "test.h"
void main()
{
test t1 ;
t1.printwindow() // OK I have declared function so my _WINDOWS_ is available but when i run it i get
}
Error Code : error lnk2019 unresolved external symbol public
NOTE : if i define the function directly it works without any problem
// test.h
class Test
{
public:
#if defined (_WINDOWS_)
void printwindow(){couT << "i am window" }
#endif
void notwindows();
};
but I don’t like this method. I prefer to define them in separate files (h and cpp).
It would be better for you to use
_WIN32instead of_WINDOWS_for your conditional compilation test._WINDOWS_is defined only ifwindows.hhas been included, while the compiler automatically defines_WIN32for any build for a Windows target, regardless of what headers are included. In your situation,_WINDOWS_is defined when you compilemain.cppbut not when you compiletest.cppbecuasetest.cppdoesn’t includewindows.h.Also, the
_WINDOWS_macro definition is an implementation detail of thewindows.hheader, and is not guaranteed to be used. For example, the MinGW version ofwindows.hdoes not define_WINDOWS_.