c - Visual Studio C 编译器未将头文件链接到其源对应文件

标签 c visual-studio struct header linker

我正在使用 VS 并使用 C 语言编写我的第一 block 可重用代码,因此我将代码分为头文件和源文件,这导致了一些意外的行为。

在我看来,不知何故,链接器无法解析我的类型定义结构。我尝试将实际的结构声明移至实现文件中,并从头文件中对结构进行类型定义,但没有成功。

为了简洁起见,我删除了所有实现,因为这不是问题。

// queue.h
#ifndef INC_QUEUE_
#define INC_QUEUE_

#include <stdint.h>

// STRUCT TYPEDEF
typedef struct QueueElement { ... } QueueElement;
typedef struct Queue { ... } Queue;

// FUNCTION PROTOTYPES
Queue* queue_construct();
uint32_t queue_peek(Queue *);
void queue_enqueue(Queue *, uint32_t);
uint32_t queue_dequeue(Queue *);
uint8_t queue_empty(Queue *);
void queue_destroy(Queue *);

#endif


// queue.c
#include <stdlib.h>
#include "queue.h"

Queue* queue_construct() { ... }
uint32_t queue_peek(Queue *queue) { ... }
void queue_enqueue(Queue *queue, uint32_t element) { ... }
uint32_t queue_dequeue(Queue *queue) { ... }
uint8_t queue_empty(Queue *queue) { ... }
void queue_destroy(Queue *queue) { ... }

源代码一切都很好,都可以编译,但是当我尝试将其包含在例如中时这个文件...

#include <stdio.h>
#include "queue.h"

int main()
{
  Queue *q = queue_construct();
  queue_destroy(q);
  return 1;
}

我的链接器一直给我的错误:

error LNK2019: unresolved external symbol "struct Queue * __cdecl queue_construct(void)" (?queue_construct@@YAPAUQueue@@XZ) referenced in function _main
error LNK2019: unresolved external symbol "void __cdecl queue_destroy(struct Queue *)" (?queue_destroy@@YAXPAUQueue@@@Z) referenced in function _main

任何帮助将不胜感激,这可能是一个愚蠢的问题,但正如我所说,我从未在 VS C 中处理过“更大/多文件”项目。

编辑
有人向我指出,包含 main 函数的源文件确实位于 cpp 源文件内,但我的 header 和实现位于 C 文件内。据我所知,您可以在 C++ 代码中的任何位置使用 C 文件,一个例子就是能够在 C++ 中使用任何 C 系统库。

该程序现在工作正常,但现在我的问题是:为什么我不能在 cpp 文件中使用 C header ?为什么这里会出现这样的情况呢。显然我错过了一些重要的事情。

最佳答案

在一些评论的帮助下,问题是我的主程序是在 cpp 文件中编写的,并且包含我自己的 c 头文件。愚蠢的是,我没有意识到你不能简单地在 C++ 中使用 C 库。

简单地将主文件转换为 C 源文件即可解决该问题。

这不是我需要的,因为我需要我的源文件是 C++ 格式的,所以只需搜索一下,解决方案很简单。我只需要像这样更改我的主 cpp 源文件:

// main.cpp
#include <stdio.h>

extern "C" {
  #include "queue.h"
}

int main()
{
  Queue *q = queue_construct();
  queue_destroy(q);
  return 1;
}

希望这可以防止其他人犯我所犯的同样幼稚的错误。

关于c - Visual Studio C 编译器未将头文件链接到其源对应文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29435338/

相关文章:

visual-studio - Visual Studio 2017 在调试时挂起?

ios - 需要帮助在Swift中按时间戳对结构进行排序

C++ - 将数据传递给结构

c - 使用 ShellExecuteEx() 将 UAC 窗口置于顶部

c++ - 如何在调用 fclose() 之前判断流是否在 C 中关闭

c++ - VS 2010 c++ 路径显示在项目属性中但不在 *.vcxprojf 或 *.sln 文件中?

c# - Visual Studios C# - 页面刷新时重新调用类

struct - 如何动态清除类型结构实例的值

c - getter 方法的互斥量导致死锁

c++ - 在 C/C++ 中启用高对比度模式