Mail Archives: djgpp/2001/02/09/11:15:49
Well, the linker encounters 2 copies of the function definition of the
function "sqr". When the preprocessor went through your C source code files
(calc.c and list2101.c), the code
#include "calc.h"
would be replaced by the content of "calc.h". So when your C source code
files are sent to the compiler, it actually looks like this:
/*list2101.c*/
... <== replaced by contents of stdio.h (not shown here)
long sqr(int x); <== note that this line has been replaced by preprocessor
too
int main()
{
int x;
printf("Enter an integer value: ");
scanf("%d", &x);
printf("\nThe square of %d is %ld.\n", x, sqr);
return;
}
------------------------------
/*calc.c*/
long sqr(int x); <== note that this line has been replaced by the
preprocessor
long sqr(int x)
{
return ((long)x * x);
}
-------------------------------
So the linker is confused when the same function is defined twice. I would
suggest you edit your "calc.h" as follows:
-------------------------------
#ifndef CALC_H <== Add this line
#define CALC_H <== Add this as well
/*calc.h*/
long sqr(int x);
#endif <== And lastly, don't forget to add this too.
-------------------------------
See if it solves your problem. It should work.
Yong-Kwang Goh
Singapore
KBZDj wrote:
> I am a c/c++ novice, trying to teach myself with the aid of a couple of
> books and DJGPP and RHIDE. I have just been trying my first attempt at
> including my own header files - but cannot get anywhere. So please can
> anyone help - and sorry for bringing up what is probably a very simple
> problem. The problem is described below - could any replies be sent
> direct to me because I have not subscribed to the mailing list.
>
> PROBLEM
> Using RHIDE, I have 2 c files each of which #includes a header file. The
> code is straight from a Teach Yourself C book. The source files compile,
> but I cannot link them to create an EXE. When building (compiling and
> linking) the files I get the following message:
>
> Compiling: calc.c
> no errors
> Compiling: list2101.c
> no errors
> Creating test.exe
> Error: calc.o: In function 'sqr':
> calc.c(4) Error:multiple definition of 'sqr'
> o:calc.c(4) Error:first defined here
> Error: collect2: ld returned 1 exit status
> There were some errors
>
> The source code of the 3 files is:
>
> /*list2101.c*/
> #include <stdio.h>
> #include "calc.h"
>
> int main()
> {
> int x;
>
> printf("Enter an integer value: ");
> scanf("%d", &x);
> printf("\nThe square of %d is %ld.\n", x, sqr);
> return;
> }
> ------------------------------
> /*calc.c*/
> #include "calc.h"
>
> long sqr(int x)
> {
> return ((long)x * x);
> }
> -------------------------------
> /*calc.h*/
> long sqr(int x);
>
> Any help is greatly appreciated.
> Bruce Carlisle
- Raw text -