Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to forward typedef'd struct in .h

I have Preprocessor.h

#define MAX_FILES 15  struct Preprocessor {     FILE fileVector[MAX_FILES];     int currentFile; };  typedef struct Preprocessor Prepro;  void Prepro_init(Prepro* p) {     (*p).currentFile = 0; } 

I realized then that I had to separate declarations from definitions. So I created Preprocessor.c:

#define MAX_FILES 15  struct Preprocessor {     FILE fileVector[MAX_FILES];     int currentFile; };  typedef struct Preprocessor Prepro; 

And Preprocessor.h is now:

void Prepro_init(Prepro* p) {     (*p).currentFile = 0; } 

That obviously, doesn't work because Pr..h doesn't know Prepro type. I already tried several combinations, none of them worked. I can't find the solution.

like image 421
erandros Avatar asked Aug 31 '11 15:08

erandros


People also ask

Can you forward declare a struct?

In C++, classes and structs can be forward-declared like this: class MyClass; struct MyStruct; In C++, classes can be forward-declared if you only need to use the pointer-to-that-class type (since all object pointers are the same size, and this is what the compiler cares about).

Can you forward declare a typedef C++?

namespace rapidjson { typedef Value; } class Thing { Thing( const rapidjson::Value& v ); ... }; But you can't forward declare a typedef.

Can we typedef in declaring structure?

In C++, declaring a struct or class type does allow you to use it in variable declarations, you don't need a typedef . typedef is still useful in C++ for other complex type constructs, such as function pointers.

How do you use typedef and struct?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.


2 Answers

Move the typedef struct Preprocessor Prepro; to the header the file and the definition in the c file along with the Prepro_init definition. This is will forward declare it for you with no issues.

Preprocessor.h

#ifndef _PREPROCESSOR_H_ #define _PREPROCESSOR_H_  #define MAX_FILES 15  typedef struct Preprocessor Prepro;  void Prepro_init(Prepro* p);  #endif 

Preprocessor.c

#include "Preprocessor.h"  #include <stdio.h>  struct Preprocessor {     FILE fileVector[MAX_FILES];     int currentFile; };  void Prepro_init(Prepro* p) {     (*p).currentFile = 0; } 
like image 170
Joe Avatar answered Oct 17 '22 01:10

Joe


If you want to hide the definition of Preprocessor, you can simply put this in the header file :

struct Preprocessor; typedef struct Preprocessor Prepro; 

But more generally, you'll probably also need the Preprocessor definition in the header file, to allow other code to actually use it.

like image 24
Sander De Dycker Avatar answered Oct 17 '22 01:10

Sander De Dycker