首页 文章

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

提问于
浏览
0

我有一个非常奇怪的预编译头问题 . 当我在.cpp文件中实现方法时,链接器生成LNK2019:未解析的外部符号错误 . 但是,如果我在.h文件中实现方法,则可以编译该程序 . 我碰巧找到了解决方案,但我不知道这个错误的根本原因 .

我的项目结构看起来像这样

  • 项目1

  • 项目2

项目1有3个文件 . A.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"
...

在项目2中 . 我想使用A类 .

file whatever.cpp

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

在编译时,链接器报告A构造函数的未解析外部符号错误 . 如果我在A.h文件中实现构造函数 . project2可以成功编译 . 我想知道,为什么不能把实现放在A.cpp文件中?组织预编译头的正确方法是什么?

谢谢

1 回答

  • 1

    项目2不包括A构造函数的定义 - 一种让它可见的方法是在头文件中包含定义(你做了) .

    另一种方法是在项目2中包含A.cpp文件 .

    第三种方法是使用.def文件或使用 dllexport 指令导出A类或A构造函数 .

    把它放在预编译的头文件中:

    // 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
    

    然后在A标头中声明A类:

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

    要么:

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

相关问题