views:

361

answers:

1

Hi all,

I had a very weird problem with precompile header. The linker generates LNK2019: unresolved external symbol error when I implement method in .cpp file. However, the program could be compiled if I implement method in .h file. I happened to find out a solution but I have no idea about the root cause of this error.

My project structure looks like this

Solution
->project 1
->project 2

Project 1 has 3 files. A.h, A.cpp and stdafx.h

file A.h
#pragma once
class A
{
public:
    int num;
    A();

};

file A.cpp
#include "stdafx.h"
    A::A()
      {
          num = 2;
      }

file stdafx.h
...
#include "A.h"
...

In project 2. I want to use A class.

file whatever.cpp

#include "stdafx.h"
#include "../Project1/A.h"
...
    A* a_obj = new A();
...

In compile time, the linker reports unresolved external symbol error for the A construction function. If I implement the constructor in A.h file. the project2 could be successful complied. I want to know, why can not put the implementation in A.cpp file? What is the right way to organize precompile header?

Thank you

+1  A: 

Project 2 does not include the definition of the A constructor - one way to give it visibility of this is to include the definition in the header file (which you did).

Another way would be to include the A.cpp file in project 2.

A third way would be to export the A class, or the A constructor using a .def file or using the dllexport directive.

Put this in the precompiled header file:

// set up export import macros for client project use
// define the symbol "PROJ1" before including this file in project 1 only
// leave it undefined for other projects
#ifdef PROJ1
#define DLLEXP __declspec(dllexport)
#else
#define DLLEXP __declspec(dllimport)
#endif

Then declare the A class in the A header:

DLLEXP class A
{
  public:
    A();
   ...
};

Or:

class A
{
  public:
    DLLEXP A();
   ...
};
1800 INFORMATION
Thank you, The second approach works well for me
LNK2019