第一次使用PCH,获取链接器工具错误

时间:2017-09-27 04:00:37

标签: c++ c visual-studio pch

我是一个非常新手的程序员,只是学习了一点c,但我总是在Linux上用gcc和Vim做过但是我决定尝试使用visual studio并且我得到了LNK2005和LNK1169错误,我已经尝试查找错误以及如何修复它们并正确使用PCH,因为我认为即使我的程序太小而无法使用它也会很有用。

根据我的理解,我需要在我的源文件顶部#include "stdafx.h"(称为&#39; helloworld.c&#39;)我还没有触及&#39; {{ 1}}&#39;从我创建项目时出现的默认设置开始,我创建了一个名为&#39; stdafx.c&#39;的标题文件。并且它有一个名为&#39; bitwise.h&#39;然后我有&#39; int bw()&#39;我添加的所有内容都是stdafx.h在我的标题#include "bitwise.h"中,我试图包含bitwise.h,甚至不包含任何内容。所有这些都打破了我的计划。我可以编译它的唯一方法是,如果我注释掉#include "stdafx.h" #include "stdafx.c" #include <stdio.h>,那么我的程序编译得很好。

这里是我认为可能是罪魁祸首的文件:

helloworld.c

//bw();

bitwise.h

#include "stdafx.h"

int main()
{

    printf("\tHello World!\n");
    getchar();
    bw(); //If this line is commented out everything works just Honky-Dory
    getchar();
    return 0;
}

stdafx.c

#include "stdafx.h" //I've tried lots of diffrent lines here, nothing works

int bw()
{
        int a = 1;
        int x;

        for (x = 0; x < 7; x++)
        {
            printf("\nNumber is Shifted By %i Bits: %i", x, a << x);
        }
        getchar();

        return 0;
}

stdafx.h中

// stdafx.cpp : source file that includes just the standard includes
// $safeprojectname$.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

2 个答案:

答案 0 :(得分:0)

Nitpick:你不应该在bitwise.h中#include stdafx.h,尽管它应该仍然有#pragma一次。

bw()的代码仍应位于单独的bitwise.c文件中,而不应位于标头中。我认为你可能会混淆预编译头与函数内联?现在,bw的代码被编译成虚拟stdafx对象,并再次在主对象中,并在链接时导致冲突。

另外,您是否记得将stdafx.h标记为预编译标题(/ Yu),将stdafx.cpp标记为...无论/ Yc应该是什么意思?确保为属性中的两个文件的所有项目配置设置了两个选项 - &gt; C / C ++ - &gt;预编译标题。

答案 1 :(得分:0)

这与PCH无关。您混合了标题(.h)和实现(.c)文件。您需要做的是拆分实现和声明。你应该这样做:

  1. 将您的bitwise.h重命名为bitwise.c,因为这是您的实施文件,而不是标题!

  2. 创建一个新文件bitwise.h并只在那里放置声明,它应该如下所示:

    #pragma once
    
    int bw();
    
  3. 之后你的项目应该可以编译。

    另请注意,PCH文件应包含不经常更改的包含,这可能不是您的情况,因为您还包括bitwise.h。您可能希望从stdafx.h中删除此包含,并将其包含在helloworld.c

    只是旁注,在学习C 期间想到通过#include包含.c文件!如果它修复了一些编译错误,那么您的项目设计可能非常错误。