Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why redefinition of a function which is already present in dynamic or static library does not throw any error?

Wy redefinition of function already present in dynamic library does not throws any compilation and linking error?

In the below function

#include "calc_mean.h"
#include <stdio.h>

int mean(int t, int v) {
  return 0;
}

int main () {
  int theMean = mean(3,6);
  printf("\n  %d\n",theMean);
}

Inside the shared library Definition of mean function already present as below.

#include <stdio.h>
#include "calc_mean.h"

int mean(int a, int b) {
  return (a+b)/2;
}

The definition of mean function is already present in the shared library libmean.so. But during compilation I don't see any redefinition error and compilation is successful.

And on successful execution the o/p I see is 0 instead of 4 so the function definition of mean inside the shared library is not getting executed but the one inside the main module is getting executed.

Why is this happening so?

like image 397
Abhishek parikshya Avatar asked Jun 24 '14 15:06

Abhishek parikshya


People also ask

How do you solve redefinition error?

Re “How do you fix a redefinition error in C programming?”, you do that by removing the redefinition. Compilers can get confused when subjected to unexpected repetition in source code. So when they complain about it, the fix is to find and remove the repetition.

What does redefinition mean in C++?

A redefinition is an attempt to redefine the same variable, e.g.: int a = 5; int a = 6; Also. int foo(); is not a definition. It's a declaration.

What is whole archive?

The /WHOLEARCHIVE option forces the linker to include every object file from either a specified static library, or if no library is specified, from all static libraries specified to the LINK command.


1 Answers

The linker only links in a function from a library if the function had not yet been found during the compilation/linking process.

The reason for the difference in functionality is that there are different types of symbols. A library function is a weak symbol. It is only included if it is not already defined. nm is a tool for listing the symbols in an object or executable. In its man-page you can find a list of the types of symbols.

There is also a wikipedia page on weak symbols.

like image 79
alk Avatar answered Sep 28 '22 16:09

alk