0

I have a C++ project containing multiple classes defined in separate .h and .cpp files.

As I add more and more classes to the project, I find myself using functions that should be part of a shared library (utility functions).

I tried adding all utility functions in a separate file, and only include it in files that require their use.

That works and the compiler will not complain unless I try to include that utility file in multiple class files. (As long as I only include the file once, and only once).

What can I do to include the utility file in multiple files?

I already tried the compiler declaratives to avoid including more than one copy of the file:

util.h

#ifndef UTIL_H
#define UTIL_H

#include <libraries_used_here>

<< shared functions code here >>

#endif // UTIL_H
Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • Don't *define* functions or variables in header files, as then they will be defined in all translation units where the header files is included. – Some programmer dude Nov 04 '19 at 09:14
  • @Someprogrammerdude then where shall I define the shared functions? – Ahmad Nov 04 '19 at 09:15
  • In a source file? Like `utils.cpp`? Or make the functions `inline` or `static` (which also does other things and I really don't recommend). – Some programmer dude Nov 04 '19 at 09:17
  • I renamed the file from `util.h` to `util.cpp` and update the include statements, but got the same error (duplicate symbol) @Someprogrammerdude – Ahmad Nov 04 '19 at 09:19
  • Don't include cpp files. – Jarod42 Nov 04 '19 at 09:20
  • @Jarod42 then how does the compiler know where to find the definition of the shared function if I don't include the source file? – Ahmad Nov 04 '19 at 09:22
  • In the C++ ecosystem we include headers that usually contain declarations only, for stuff to be found elsewhere. cpp files are compiled separately into object files with missing symbols and exported symbols. As a final stage the linker takes all the objects files and matches missing and exported symbols as part of aggregating the object files into a single executable. – StoryTeller - Unslander Monica Nov 04 '19 at 09:26
  • You should put function *declarations* in the header file, then the compiler will know that the functions exists somewhere. Then you put the definitions (implementations) of the functions in a source file that you build like all your other source files. – Some programmer dude Nov 04 '19 at 09:30

0 Answers0