How should I include variable defined with extern in c file - c

I am having trouble compiling the demonstration code for the STM32F4-Discovery using the arm-none-eabi toolchain. The error is occuring in linking and this is the [first] error I'm receiving.
template/obj/stm32f4xx_it.o: In function `OTG_FS_IRQHandler':
template/src/stm32f4xx_it.c:192: undefined reference to `hpcd'
I've been trying to figure this out on and off for several months so I've created this github repository to track the project. The variable hpcd is defined in template/src/usbd_conf.c. My knowledge of C/C++ is unfortunately full of holes, so I'm hoping someone may help me both narrow down the problem and the suggest the proper way to fix it.
I have two questions.
hpcd is included in the file usbd_conf.c. It is used in many files, but none of these files actually include usbd_conf.c, only usbd_conf.h. The question is, by only including the header, can a file which declares a variable as extern PCD_HandleTypeDef hpcd; use the variable without specifically including the .c file?
Assuming the answer to question 1 is yes, why is it the function OTG_FS_IRQHandler isn't finding hpcd? The chain of includes from stm32f4xx_it is main.h -> usbd_core.h -> usbd_conf.h.
I'm assuming the answer to question 1 is yes because this is the demonstration code I believe was running on the board when I purchased it. I can only assume the poblem is with the way I'm building it. Would anyone be willing to help me troubleshoot this problem? I would be happy to provide more details if relevant or to better structure this question, but I'm trying to avoid posting a full USB stack in my question. Thank you.

It might help if you put extern PCD_HandleTypeDef hpcd; in one of the headers that gets included by everyone involved (main.h would do, I think).
Example for how the extern stuff works normally:
A file that does define a variable you want to use elsewhere contains
include "a_header.h";
// ...
int some_variable = 42;
The header a_header.h contains
extern some_variable;
The file where you want to use that variable contains
include "a_header.h";
extern some_variable;
//...
foo = some_variable;
some_variable = 47;
such that the linker knows excactly what to do with it.

Related

C Guard not work as intended with rlutil.h

I'm trying to use rlutil.h but everytime these function are used in more than one header I have compiler error about multiple definition of 20-30 variables. rlutil is a simple header to color terminal in linux and windows in C and C++.
The variables are something like that
const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_POST = "\007";
and the typedef something like that
typedef const char* RLUTIL_STRING_T;
I tried to add my own C guard but it didn't worked.
I tried to layering the .h with my own .h/.c to make new function using the rlutil.h function but the problem is still here.
I tried to make the variables extern but it's worst
I'm building it with gcc on ubuntu.
I'm gonna try this at home with MVSC2017 but I think the behavior will be the same.
Any idea ?
I can provide more information.
Sorry for my english i'm not a native speaker
Thank's a lot
The problem is that the header is only set up so that it works with C++, where the const values defined in the header rlutil.h are private to each translation unit (TU) — think source file plus headers — that includes the header. By contrast, in C, they are normal global variables defined in each TU that includes rlutil.h, leading to the multiple definitions problem.
There isn't a trivial fix — unless switching from C to C++ is deemed trivial. The header attempts to be language-neutral between C and C++, but it fails on this count. Once again, proof that C and C++ are different languages.
In C, you would need to have code like:
extern const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_POST;
in the header and then one source file would define the values:
const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_POST = "\007"; // James Bond!
Alternatively, you could consider using static in the header:
static const RLUTIL_STRING_T ANSI_CONSOLE_TITLE_POST = "\007";
Each C file that includes this header would have its own collection of defined variables. In C, you'd be subject to compiler warnings about unused variables, which is not desirable. In C++, you might get warnings about using static instead of an anonymous namespace. It isn't clear that this is a good solution, therefore.
If you're brave, you could read the tail end of my answer to How do I use extern to share variables between files, but the header is probably not in your control and you really need to report the trouble to the maintainers of the code. (If you are the maintainer, then think about whether a scheme such as that outlined in the answer to the other question will help.)

Accessing a typedef globally

I found some source code that I want to incorporate into a C program I am writing. Let's call it existing.c. This file contains a typedef for a struct that is required for a parameter to a function defined lower down in the file. I want to call this function in my file main.c. I know I could probably get access to the function by declaring a function prototype in main.c, but I will also need access to that struct definition to declare and call the function.
There is no .h file for existing.c, although I could of course make one, say existing.h. But if I put the typedef in existing.h, then it seems like I would have to put #include "existing.h" into existing.c, which does not seem correct from my understanding of header files. I thought their purpose was to make the code in a certain file available to other compilation units, and shouldn't be required by that file itself.
So I guess my main question is straightforward, how do I use the function defined in existing.c in my own file main.c? Can I do it without a header file, like by putting some kind of struct prototype in main.c, similar to a function prototype, or specify the struct as external or something along those lines?
Edit: I probably should have mentioned in my original post that one reason I was hoping to avoid using a header was so I could incorporate the existing.c file unaltered in case there are revisions of this source in the future. Judging from the answers this is not possible.
if I put the typedef in existing.h, then it seems like I would have to put #include "existing.h" into existing.c, which does not seem correct from my knowledge of header files.
That is precisely the thing to do: move the typedef into the existing.h header, then include that header in both the existing.c and in your code.
I thought their purpose was to make the code in a certain file available to other compilation units, and shouldn't be required by that file itself.
That is how the headers do their job - you include them both from the implementation file and from the code that uses that implementation.
Although it is possible to write a header that matches what was in the implementation, and use it without inclusion in the implementation file itself, this is not desirable: one reason why you include the header in the implementation is to let the compiler check the code against the function prototypes from the header, and produce errors for any discrepancies it may find.
then it seems like I would have to put #include "existing.h" into existing.c, which does not seem correct
That's the proper and correct way to do it.
You place declarations in a header file if more than one compilation unit needs those declarations, and the source code file containing the implementation is almost always one of the files you include the header file in.

C using a forward declaration within a function definition

I'm working on a project in which I'm forced to use some previously written code that uses many header files calling other header files. I'm trying to keep my application separated, but I still need to use many of the types and functions defined in the previous code.
I've added forward declarations in my own header files, when referencing data types declared in other header files. My problem now, is I'm trying to reference a union type from within a function definition in a source file and I'm not quite sure how to do it.
Old header file:
/* filename: include.h */
typedef union SOME_UNION_TYPE
{
int a;
.
.
}SOME_UNION_TYPE;
My source file:
/* filename: file.c */
void func()
{
SOME_UNION_TYPE A;
.
.
return;
}
I know it would be easier to just include "include.h" in my source code, but I'm trying to avoid it as much as possible. My attempt so far has been to forward declare the union in my header file, in hopes of exposing the typedef name to the compiler.
My header file:
/* filename: file.h */
union SOME_UNION_TYPE;
However, when I compile, I receive an error complaining about unknown size for A in func().
Thanks in advance for any help.
If you need to create an actual instance of the type, you need the complete declaration, not just the name.
The right thing to do in this case is to bite the bullet and include the header file that defines the type.
The #include directive is not something to be avoided. If you're concerned about other people's code polluting your code, you can make a header that includes the headers you need, and include that one directly.
Duplicating code is bad.
The other code probably includes a bunch of other headers because it needs them! You should just include the other header otherwise you are duplicating code which is bad.

Modular programming in C (nested headers)

I'm creating a large program that's supposed to be simulating a MIPS pipeline. I'm trying to modularize my code as much as possible to keep things simple, but I'm having trouble compiling.
Currently my program contains the files:
pipe.c --- Containing main
IF.h
ID.h
EX.h
MEM.h
WB.h
global.h --- containing global #define functions
reg.h
ALU.h
control.h
dMem.h
fBuffer.h
parser.h
bin.h
I'm new to C programming but I have protected myself against multiple includes using #ifndef, #define, #endif in every header file. My problem is that when I compile I get errors claiming: "previous implicit declaration of..."
Many of the header files are used by multiple files, so I'm not sure if this is the issue. Is there some sort of big thing that I'm missing?
an implicit declaration means that there was something that wasn't declared in a header (instead, the compiler simply found the function). a previous implicit declaration means that it's come across the declaration later, after assuming an implicit declaration for a "raw" function (or, i guess, as Doug suggests in the comments, another function with the same name).
there are a number of ways this can occur:
maybe you didn't include the header in the associated file. so IF.c doesn't include IF.h. the compiler will read IF.c and create the implicit definition. later, when it reads IF.h somewhere else, it will give this error.
maybe you use a function in a file that doesn't include the relevant header. so maybe IF.h defines myfunction(), but you use myfunction() in dMem.c and don't include IF.h there. so the compiler sees the use of myfunction() in dMem.c before it sees the definition in IF.h when included in IF.c.
without header files at all, you can get this with mutually recursive functions. see How to sort functions in C? "previous implicit declaration of a function was here" error
as Doug suggested, you define two functions with the same name (and don't have a definition in a header).
basically, somewhere, somehow, the compiler got to a function before it got to the header with the associated declaration. when it did find the header it realised things were messed up and generated the error.
(one classic source of header errors is cut+paste the "ifdefs" from one file to another and forget to change the name...)
[reading your question again i assumed you'd only listed the header files. but now i see that is all the files you have. why do you have so many more headers than source files? typically each source file is associated with one or two headers that contain the declarations for the functions it defines (although it will likely import others that it needs for support). this is unrelated to your compiler error, but it sounds like maybe you need to split your source up. it also suggests that either i have misunderstood you, or you are misunderstanding how headers are typically used.]

Why should I include an header file? And how #include actually works? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
At first, I was writing my function in an .h file and then include it with #include "myheader.h". Then, someone said me that it's better to add to these files only functions prototypes and to put the real code in a separate .c file.
Now, I'm able to compile more .c files to generate only an executable, but at this point I can't understand why I should add the header files if the code is in another file.
Moreover, I had a look to standard C libraries (like stdlib.h) in the system and it seemed to me to store only structure definitions, constants and similar... I'm not so good with C (and to be honest, stdlib.h was almost Chinese to me, no offense for Chinese of course :) ), but I didn't spot any single line of 'operative' code. However, I always just include it without adding anything else and I compile my files as if the 'code' was actually there.
Can someone please explain me how do these things work? Or, at least, point me to a good guide? I searched on Google and SO, also, but didn't find anything that explains it clearly.
When you compile C code, the compiler has to actually know that a particular function exists with a defined name, parameter list, return type and optional modifiers. All these things are called function signature and the existence of a particular function is declared in the header file. Having this information, when the compiler finds a call to this function, it will know which type of parameters to look for, can control whether they have the appropriate type and prepare them to a structure that will be pushed to the stack before the code actually jumps to your function implementation. However the compiler does not have to know the actual implementation of the function, it simple puts a "placeholder" in your object file to all function calls. (Note: each c files compiles to exactly one object file). #include simple takes the header file and replaces the #include line with the contents of the file.
After the compilation the build script passes all object files to the linker. The linker will be that resolves all function "placeholders" finding the physical location of the function implementation, let them be among your object files, framework libraries or dlls. It simple places the information where the function implementation can be found to all function calls thus your program will know where to continue execution when it arrives to your function call.
Having said all this it should be clear why you can't put function definition in the header files. If later you would #include this header in to more then one c file, both of them would compile the function implementation into two separate object files. The compiler would work well, but when the linker wanted to link together everything, it would find two implementation of the function and would give you an error.
stdlib.h and friends work the same way. The implementation of the functions declared in them can be found in framework libraries which the compiler links to your code "automatically" even if you are not aware of it.
The C language (together with C++) uses a quite obsolete strategy for making the compiler know the functions defined elsewhere.
This strategy goes like this: the signatures of the functions etc. (this stuff is called declarations in C) go into a special file called header, and every other file which wants to use them is expected to almost literally include that header into the file (actually, #include directive just tells the compiler to include the literal text of the header), so that the compiler sees again the function declarations.
Other languages solve this problem in a different way: compiler sees all the source code, and remembers the metadata of the already compiled classes itself.
The strategy used in C shifts the task of finding all the dependencies from the compiler to the developer; it's a legacy from the old times when the computers were small, silly and slow, so this kind of help from the developer was really valuable.
Although this strategy has numerous drawbacks, and besides it's theoretically possible to change it now, the standard is not going to change, because gigabytes of code have been written in that style already.
tl;dr: it's a legacy from the 70's.
In C it is required that a function is declared before it is called. The reason this is required was that in the 70s it would just take too much time to first parse a file for all its symbols and then parse it a second time to actually compile the code. If all functions are declared before they are called one single parse is enough. However on modern system we no longer face those limitations and that is the reason why mondern languages don't have this requirement.
Imagine you have 2 files a.c b.c in your project. You implement a function foo which you want to use in both files. You can't just define the function in a.c and use it in b.c since you have to declare a function before you call it. So you would add a line void foo(); to b.c. But everytime you change the signature of your function in a.c you would have to change the declaration in b.c. To circumvent this issue it is standard strategy in C to declare all functions your file implements in a seperate header file (in this case a.h. The header file is then included by all other files who want to use that code (so b.c would use this: #include "a.h").
An #include is a preprocessor directive that causes the file to be textually inserted at the point where the #include occurs.
When linking multiple .c files that include the same header files, care must be taken to avoid multiple inclusions of the header files (textually inserting a header file more than once). The #ifndef, #define, and #endif preprocessor directives can be used to prevent multiple inclusions.
#ifndef MY_FILE_H
#define MY_FILE_H
/* This code will not be included more than once. */
#endif /* !MY_FILE_H */
I can't understand why I should add the header files if the code is in another file.
The header file contains the declarations for functions defined in the other file, which is necessary for the code that's calling the function to compile correctly.
For instance, suppose I write the following code:
int main(void)
{
double *foo = malloc(sizeof *foo * 10);
if (foo)
{
// do something with foo
free (foo);
}
return 0;
}
malloc is a standard library function that dynamically allocates memory and returns a pointer to it. The return type of malloc is void *, any value of which can be assigned to any other pointer type. free is another standard library function that deallocates memory allocated through malloc, and its return type is void (IOW, no return value).
However, the compiler doesn't automatically know what malloc or free return (or don't return); it needs to see the declarations for both functions in the current scope before it can correctly translate the function calls. Under the C89 standard and earlier, if a function is called without a declaration in scope, the compiler assumes that the function returns int; since int is not compatible with double * (you can't assign one to the other directly without a cast), you'll get an "incompatible assignment" diagnostic. Under C99 and later, implicit declarations aren't allowed at all. Either way the compiler won't translate the code.
I need to add the line
#include <stdlib.h>
which includes the declarations for malloc and free (and a bunch of other stuff) to the beginning of the file.
There are several reasons you don't want to put function definitions (or variable definitions) in header files. Suppose you define function foo in header a.h. You include a.h in files a.c and b.c. Each file will compile okay individually, but when you try to link them together to build a library or executable, you'll get a "multiple definition" error from the linker -- you've wound up creating two separate instances of a function with the same name, which is a no-no. Same goes for variable definitions.
It also doesn't scale well. If you put a bunch of functions in their own header files and include them in one source file, you're translating all those functions in one big glob. Furthermore, if you only change the code in the source file or one header file, you still wind up recompiling everything each time you recompile the .c file. By putting each function in it's own .c file, you can reduce your overall build times by only recompiling the files that need to be recompiled.

Resources