0

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

据我了解,我需要#include "stdafx.h"在我的源文件(称为' helloworld.c')的顶部,我没有stdafx.c从创建项目时的默认值中触及'',我创建了一个名为' bitwise.h'的头文件,它有一个功能它叫' int bw()'然后我有' stdafx.h',我添加的只是#include "bitwise.h"在我的标题中,我bitwise.h试图包含#include "stdafx.h" #include "stdafx.c" #include <stdio.h>甚至不包含任何内容。所有这些都破坏了我的程序。我可以编译它的唯一方法是如果我注释掉//bw();然后我的程序编译就好了。

以下是我认为可能是罪魁祸首的文件:

你好世界.c

#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;
}

按位.h

#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.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

标准数据文件

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"
#include "bitwise.h"
#include <stdio.h>
#include <tchar.h>



// TODO: reference additional headers your program requires here
4

2 回答 2

0

Nitpick:您不需要在 bitwise.h 中包含 #include stdafx.h,尽管它仍然应该有一个 #pragma once。

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

此外,您是否记得将您的 stdafx.h 标记为预编译头文件 (/Yu),并将 stdafx.cpp 标记为...无论 /Yc 应该是什么意思?确保在 Properties -> C/C++ -> Precompiled Headers 中为两个文件的所有项目配置都设置了这两个选项。

于 2017-09-27T04:23:36.433 回答
0

这与 PCH 无关。您混淆了头文件 (.h) 和实现 (.c) 文件。您需要做的是拆分实现和声明。您应该执行以下操作:

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

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

    #pragma once
    
    int bw();
    

之后您的项目应该能够编译。

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

顺便说一句,在学习 C 的过程中,不要考虑通过 .c 文件#include!如果它修复了您的一些编译错误,那么您的项目设计可能非常错误。

于 2017-09-27T05:10:21.007 回答