0

From what I have been seeing from C++ code examples, if I have two files Log.cpp and Math.cpp

in Math.cpp we have,

#include <iostream>

void Log(const char* message);

static int multiply(int a, int b){
    Log("Multiply");
    return a * b;
}

in Log.cpp we simply print the text that was given to us. However unlike most programming languages that I use we do not directly import the method from a specific module or file, we simply declare it in C++. For example in Python it would be from x import y, which meant that we could have multiple definitions of y but depending from where we imported it from, depended in which implementation was used. How would this works in C++ if I had multiple definitions of Log, how would it know which one to use?

Mick
  • 6,527
  • 4
  • 52
  • 67
J.Doe
  • 31
  • 4
  • 2
    Handy reading: [How does the compilation/linking process work?](https://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) You're mostly interested in the linking stage. – user4581301 Sep 10 '20 at 04:17
  • 1
    It doesn't. C++ does not work this way. If your intent is to learn C++, the most important thing to learn is to forget all other languages. C++ is not Java. C++ is not Python. C++ works in fundamentally different ways than other programming languages. – Sam Varshavchik Sep 10 '20 at 04:19
  • 1
    The way C++ handles multiple functions with the same name is to make sure they are declared in different namespaces. Then you code code call e.g. `foo::Log()` or `bar::Log()` to indicate which one it wants, or alternatively you could add a `using namespace foo;` declaration to tell the compiler which namespace you prefer to use by default. – Jeremy Friesner Sep 10 '20 at 04:34
  • How would this work when working for a company with a very large codebase? I can't imagine trying to think of a method name and then needing to double check if it already defined in some files miles away. Edit: oh I think @JeremyFriesner just answered as soon as I pressed enter lol. – J.Doe Sep 10 '20 at 04:35
  • The answer to the question in your title is that the linker finds it. Not the C++ compiler or program. – user207421 Sep 10 '20 at 04:38
  • "Every program shall contain exactly one definition of every non-inline function or variable that is [used] in that program." and "An inline function shall be defined in every translation unit in which it is [used]" [basic.def.odr](https://timsong-cpp.github.io/cppwp/n3337/basic.def.odr#3) It's not a C++ program if there are multiple definitions – Caleth Sep 10 '20 at 08:43

0 Answers0