简体   繁体   English

Visual C ++链接LNK2019错误与预编译的头

[英]Visual C++ Linking LNK2019 Error with a Precompiled Header

I had a very weird problem with precompile header. 我对预编译标头有一个很奇怪的问题。 The linker generates LNK2019: unresolved external symbol error when I implement method in .cpp file. 当我在.cpp文件中实现方法时,链接器生成LNK2019:未解决的外部符号错误。 However, the program could be compiled if I implement method in .h file. 但是,如果我在.h文件中实现方法,则可以编译该程序。 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 ->项目1
->project 2 ->项目2

Project 1 has 3 files. 项目1有3个文件。 Ah, A.cpp and stdafx.h 啊,A.cpp和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. 在项目2中。我想使用A类。

file whatever.cpp 文件every.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. 在编译时,链接器报告A构造函数的未解决的外部符号错误。 If I implement the constructor in Ah file. 如果我在Ah文件中实现构造函数。 the project2 could be successful complied. project2可能会成功完成。 I want to know, why can not put the implementation in A.cpp file? 我想知道,为什么不能将实现放在A.cpp文件中? What is the right way to organize precompile header? 组织预编译头的正确方法是什么?

Thank you 谢谢

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). 项目2不包括A构造函数的定义-一种使它具有可见性的方法是将定义包括在头文件中(您已这样做)。

Another way would be to include the A.cpp file in project 2. 另一种方法是在项目2中包含A.cpp文件。

A third way would be to export the A class, or the A constructor using a .def file or using the dllexport directive. 第三种方法是使用.def文件或dllexport指令导出A类或A构造函数。

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: 然后在A标头中声明A类:

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

Or: 要么:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM