2

I'm using the MPLAB IDE and the XC8 compiler for a C project for PIC18 devices. I'm building a project with multiple source files and don't know how to make the structure.

In the project, I have the following things:

  • A file main.c where the main code is located. From here, several files are included:
    • xc.h: to define chip-specific variables and so
    • stdlib.h, stdio.h, plib.h, delays.h: for the compiler's functions
    • enc28j60.h: a homebrew file with definitions and prototypes
  • A file enc28j60.c, where the functions of the prototypes in enc28j60.h go

I cannot compile enc28j60.c as standalone file because it depends on definitions in main.c.

I have a few questions on how to set this project up:

  1. Should I add enc28j60.c to the source files of my MPLAB project? If I do this, MPLAB tries to compile the file, which fails. If I don't do this, the linker cannot find the symbols that are defined in enc28j60.c and prototyped in enc28j60.h.
  2. Should I #include enc28j60.c from somewhere? If not, how does MPLAB know where to get the file?
  3. Should I add enc28j60.h to the header files of my MPLAB project?
  4. Should I #include enc28j60.h from somewhere? Right now, I do this in main.c, after the definitions enc28j60.h needs in order to run (and not throw #errors).
4

2 回答 2

2

我设法通过稍微修改我的库和头文件来完成这项工作。

起初,我添加了一个 main.h 文件,所有原型#defines 和#includes 都在其中。然后,在每个.h文件中,我在顶部添加了这个:

#ifndef SOME_LIB_IDENTIFIER   // makes sure the lib only gets included once,
#define SOME_LIB_IDENTIFIER   // has to be specific for every lib

#include "main.h"             // to make sure everything's initialized (this line of course not in main.h)

.h每个文件的最后一行是:

#endif

我添加#include "enc28j60.h"到 enc28j60.c 文件的顶部。现在可以编译该文件。

在 main.h 中,我为 xc.h、plib.h、stdlib.h、stdio.h 和 enc28j60.h 添加了包含。我无处包含.c文件。

我将 main 和 enc28j60 头文件和源文件都添加到我的 MPLAB 项目中。源文件都编译得很好。结果是连在一起的。

简而言之

  • 添加一个 main.h,所有原型#defines 和#includes 都在其中
  • 为所有头文件添加页眉和页脚,以确保它们只包含一次。还包括这些头文件中的 main.h,以确保每个文件都使用相同的定义
  • 在源文件的第一行包含源文件对应的 .h 文件。不要包含 .c 文件
  • 将所有头文件和源文件(未内置在编译器中)添加到 MPLAB 项目
  • Build (F10) 应该编译所有文件并将它们正确链接在一起
于 2013-05-02T10:47:24.647 回答
1

不要包含.c文件。仅包括标题。如果您有要在文件之间共享的声明,请将它们放在单独的标头中,并在需要时包含该标头。

编译每个单独的源文件后,将生成的目标文件链接在一起。这涉及在所有源文件上调用编译器,然后在目标文件上一次性调用链接器(使用补充库等)。

于 2013-04-30T17:22:16.743 回答