c++ - Namespace function linker error when used in multiple classes -


i writing function want use in code debugging without throwing exceptions. want defined variable debug_mode when set true causes function print given message , when set false prints nothing. want available class imports file without having create class, i.e. include "debug.h" , can call debug::log(string message).

i read advantages of using namespace functions wrote such perhaps don't understand proper usage of namespace functions. when include header file namespace function in 1 class works great, when use in 2 classes in 2 different files linker error:

error   1   error lnk2005: "void __cdecl debug::log(char const *)" (?log@debug@@yaxpbd0@z) defined in foo.obj... 

here code namespace functions:

#pragma once  #include <cstdio>  // important: set true if want debug logging, false otherwise #define debug_mode true  namespace debug {     void log(const char* message)     {         if (debug_mode)             printf(message);     }      void log(const char* messageformat, const char* parameter)     {         if (debug_mode)             printf(messageformat, parameter);     } } 

now if make functions static works fine, under impression using namespace functions alternative static functions in case. able define static functions in file if possible.

what should use? static function? namespace function? if latter how use namespace functions in 2 separate classes/files without causing above linker error?

all missing inline keyword so:

inline void log(const char* message) 

without inline, functions created each source file including header file.

static have similar outcome, inlining seems preferred such small functions.


or, if don't want make compiler create code again , again in files, of course need have implementation once in 1 .cpp file , leave declaration in header.

in order debug_mode affect it, though, need e.g. this:

#ifndef debug_mode  // dummy implementation inline void log(...) {}  #else  // implemented in log.cpp void log(const char* message); void log(const char* messageformat, const char* parameter);  #endif 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -