Re: [Dev-C++] multiple definition linker error
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Luigi S. <gi...@li...> - 2002-07-27 16:23:08
|
At 14.04 07/25/02 -0700, Andrew Jenkins wrote: >hi, >I call a header file (tree.h) from two c files(main.c & tree.c)... when I >do this, an int fileNo gets declared twice, because the header is called >twice, twice causing a linker error. I then add: >#ifndef TREE_H >#define TREE_H >//functions and struct here >int fileNo = 0; >#endif > >for some reason that didnt keep the compiler from reading the contents of >tree.h multiple times... im rather stumped, it almost seems like its >ignoring all the preprocessor commands except #include altogether. i cant >imagine any linker params that id need to set but im not sure. > >im running version 4.9.4.2 of dev and in compiler options, I have all 3 c >compiler options selected. > >anyone have any ideas? > >Thanks. Hi, I'll try to give an explanation, it makes sense to me, hopefully to you too. The "#ifndef" stuff, is used to avoid that a file is included more than once within the *same* compilation unit, not across *different* units. Here is an example that could better explain what I mean. "main.c" and "tree.c" are two compilation units. Each of them requires the header file "tree.h" be included. In fact "main.c" needs it because a Tree is used within function "main", and "tree.c" needs it to make sure function definitions and declarations are consistent. Suppose instead that you had this situation: - "main.c" includes the headers: "containers.h" and "tree.h" - "containers.h" includes the header "tree.h" - "tree.c" includes "tree.h" In the above situation, if you do not use the "#ifndef", you will see the content of "tree.h" included twice within "main.c" (so compilation time is a bit longer, as there is more to be parsed). If you use "#ifndef", only once will content of "tree.h" be included: since once is enough, you should always use the "#ifdef". A good rule is: always bound code, within an header file, by a "#ifndef" ... "#endif" Note that "tree.h" is included in "tree.c", without any regard of the "#ifndef", had it not been that way, keeping declarations and definitions consisten, would be a lot harder to achieve. Now an idea to solve your problem. It looks like "fileNo" is a global variable: you should only declare it within the header file "tree.h" (so that every compilation unit which uses it, knows what it is), and that define it within one compilation unit only (I guess "tree.c", since it is related to a Tree). extern int fileNo; /* this goes in "tree.h" */ int fileNo = 0; /* this goes in "tree.c" */ -- gisan |