Pyro
Pyro

Reputation: 11

How to structure a C (embedded) project with shared header and code files

This is a question of an embedded application, but I imagine the solution is language (C) based and not specific to the embedded compiler (XC16) I'm using.

Problem

I have a number of code files I am abstracting from a single project to create a shared collection of files that can be re-used across multiple projects. These files will require a config.h file in the main application to #define a number of parameters for that project.

Example

Files in project

config.h

#define BUFF_SIZE 4

main.c

#include "config.h"
#include <lib.h>
/*Application Code*/

Files in 'Library' (i.e. another folder NOT in the project structure)

lib.h

extern uint8_t Buffer [BUFF_SIZE];

lib.c

#include "lib.h"
uint8_t Buffer [BUFF_SIZE];

Question

This produces the issue that 'BUFF_SIZE is un-declared in lib.h'. My understanding was that the compiler would start in main.c load in the `#define' values from config.h THEN try to process the lib.h header. But it seems this is not the case.

Do I have to back reference the library to the config.h file? This seems to work, but it then forces the application to have specific file names.

Are there any good examples of how this sort of structuring should take place?

Additional Notes

The same issue arises when I try and map pin outputs for bit-bang functions. i.e.

config.h

#define DATA_OUT LATBbits.LATB4

lib.c

void SetPin(void)
{
  DATA_OUT = 1;
}

Cheers :)

Upvotes: 0

Views: 411

Answers (1)

Lundin
Lundin

Reputation: 213809

C code is compiled on translation unit basis. A translation unit being one single .c file and all the h files it includes. So you must include "config.h" from "lib.h".

You also need to use so-called "header guards"/"include guards" in every header. See Creating your own header file in C

Upvotes: 1

Related Questions