c++ - How are function definitions determined with header files? -
when using separate files in c++, know functions can declared using header files this:
// myheader.h int add(int num, int num2);
// mysource.cpp int add(int num, int num2) { return num + num2; }
// main.cpp #include "myheader.h" #include <iostream> int main() { std::cout << add(4, 5) << std::endl; return 0; }
my question is, in situation, how compiler determine function definition of add(int,int) when myheader.h , main.cpp have no references @ mysource.cpp?
as, if there multiple add functions (with same arguments) in program, how can make sure correct 1 being used in situation?
the function declaration gives compiler enough information generate call function.
the compiler generates object file specifies names (which, in case of c++ mangled specify arguments, namespace, cv-qualifiers, etc.) of external functions object file refers (along list of names defines).
the linker takes object files, , tries match every name refers doesn't define other object file defines same name. assigns , fills in addresses, 1 object file refers namex, fills in address it's assigning namex other file.
at least in typical case, object files looks @ include number of libraries (standard library + others specify). library collection of object files, shoved single file, enough data index data object file. in few cases, includes meta-data (for example) find object file defines specific name (obviously handy sake of faster linking, not absolute necessity).
if there 2 or more functions same mangled name, code has undefined behavior (you're violating 1 definition rule). linker usually give error message telling namez defined in both object file , object file b (but c++ standard doesn't require that).
Comments
Post a Comment