Function definition twice in C

I have a problem. I wrote this code, ahac and main.c:

file: ah

#ifndef _a_H
#define _a_H
int poly (int a, int b, int c, int x);

int square (int x)
{
       return x*x;
}
#endif // _a_H

file: ac

#include "a.h"
int poly (int a, int b, int c, int x)
{
     return a*square(x) + b * x +c;
}

file: main.c

#include <stdio.h>
#include "a.h"
int main()
{
    int p1 = poly1 (1 ,2 , 1, 5);
    int p2 = poly2 (1 ,1 , 3, 5);

    printf ("p1 = %d, p2 = %d\n", p1, p2);
    return 0;
}

and I got an error message:

/tmp/ccKKrQ7u.o: In the square function:
main.c :(. text + 0x0): multiple definition of the square
/tmp/ccwJoxlY.o:ac:(.text+0x0):
collect2 is defined here first: ld returned 1 exit status

so I moved the implementation of the squared function to the ac file and it works.

Does anyone know why?

thank

+3
source share
6 answers

, *.c *.o, *.o . *.h , *.c, , .

, #include "a.h" , *.c, () . , square(), *.o. , , .

? . *.h. *.c *.h.

+8

. .c a.h, square, .

+6

, C .c (.o), . .c .

:

  • main.c, stdio.h a.h β†’ main.o
  • a.c, a.h β†’ a.o

(ld) .o, , square(), a.h - , . , , .

​​ nm ( ),

$ nm main.o
$ nm a.o

, , square .

(Edit: , , , , , .)

+5

square() , a.c, main.c, square(), . a.c , .

, , :

static inline int square (int x)
{
       return x*x;
}

, .c, .h, square(), , , , , ,

+4

( ) , .

, , .

+1

: , , a.h.

,

static int square (int x)
{
   return x*x;
}

and add any hint your compiler uses, for example, inlineor __inlineeither.

0
source

Source: https://habr.com/ru/post/1766801/


All Articles