0

In visual studio 2012 I have a small console c++ project with the following code

Main.cpp:

#include "../TestLib/LibFunction.h"

int _tmain(int argc, _TCHAR* argv[])
{
    int number = libFunction(7);
    return 0;
}

and in a static library project LibTest I have LibFunction.h:

#pragma once

int libFunction( int a );

LibFunction.cpp

int libFunction( int a )
{
   return a + 1;
}

This compiles and runs fine. (The Library is added as a reference and linked in implicitly)

If I now add this code to main project

int libFunction( int a )
{
   return 7 * a;
}

when I try to build the program I get this error

Main.obj : error LNK2005: "int __cdecl libFunction(int)" (?libFunction@@YAHH@Z) already defined in TestLib.lib(LibFunction.obj)

which is fair enough. However if I now just try building again ( doing nothing else ) the link completes without error and the program runs fine with the new libFunction being used.

Why does the error go away? Why is there this inconsistency? Either it is valid to override a function in a library or its not. I should not get an error and then without doing anything get no error.

I am trying to understand the behaviour for a much larger project where again there are duplicate symbols defined in the exe and referenced lib and sometimes I get errors and sometimes not.

David Woo
  • 749
  • 4
  • 13
  • Looks like a bug in your toolchain. It's generally not valid to override library functions. Even if the linker *sometimes* succeeds, there's no guarantee which implementation the symbol will be resolved to unless you find a way to inform the linker. – Kenney Nov 17 '15 at 17:00
  • 1
    If this is *all* your code, the error shouldn't be there in the first place. It's robably an artifact of imcremental linking. – n. m. could be an AI Nov 17 '15 at 17:02
  • @n.m - Yes - turning off incremental building results in a build that consistently does not error. Do you want to add an answer so I can accept it? – David Woo Nov 17 '15 at 17:15

1 Answers1

1

Normally it should be OK to override library symbols. There are still caveats; for instance, if library code contains several external functions in the same source file, and you want to override one of them, you may have to override all the others. Otherwise you will get the multiple definitions error. But in this case you will get it consistently.

However such overrides may throw off the incremental linker, especially if it's the first build with the override. A full rebuild should be enough to correct the error until you add more overrides. If this is a problem, just disable incremental linking.

n. m. could be an AI
  • 112,515
  • 14
  • 128
  • 243
  • Your point about "if code contains several external functions then you need to override them all" was the actual answer to my bigger problem. – David Woo Nov 19 '15 at 10:40