"multiple definition of ..." using arpackpp - c++

in my current project I´m working with the arpackpp interface. The entire library is written in .h files, so that there is no need to compile the library. The problem I'm facing now - when I include some of the arpackpp header files in some of my files, which are not the main.cpp, I get the following errors:
/.../Files/Includes/../../../arpack++/include/arerror.h:163: multiple definition of ArpackError::Set(ArpackError::ErrorCode, std::string const&)'
/.../Files/Includes/../../../arpack++/include/arerror.h:163: first defined here
/tmp/ccruWhMn.o: In functionstd::iterator_traits::iterator_category std::__iterator_category(char* const&)':
/.../Files/Includes/../../../arpack++/include/arerror.h:163: multiple definition of ArpackError::code'
/.../Files/Includes/../../../arpack++/include/arerror.h:163: first defined here
/tmp/ccruWhMn.o: In functionstd::vector >::max_size() const':
for several arpackpp functions when linking all the .o files. As I have read in several threads the problem is that I actually include the instantiation of the functions, which should be normally avoided.
Because I don't want to change the whole library I included all classes and functions using arpackpp classes in main.cpp, which is getting quite messy. Is there a workaround to this problem? And why doesn't include guards (#ifndef...#endif) prevent this problem?

First of all, include guards do not help at this point as they only prevent multiple inclusions of a header in a "subtree" of your project files' dependency graph. In other words: If you include a header in two totally separated files of the same project, the c++ preprocessor will replace the #include <header.h> twice and independently by the code specified in the header. This is perfectly fine as long as the header only contains declarations.
In your case (and in the case of many other header-only libraries), definitions are provided in the headers as well. So unfortunately (as far as I know), there is no elegant way other than including definition-containing files once in your project. https://github.com/m-reuter/arpackpp/blob/master/include/README explicitly states which files contain definitions.
Some libraries, however, provide preprocessor macros to trigger the inclusion of definitions for the provided header files (e.g. https://github.com/nothings/stb). Maybe arpackpp provides similar mechanisms.

In general the easiest way to the work with header only libraries is to extend your code only using headers. Provided you use the correct header guards, this would remove the issue of multiple definitions of your code. If you have a large base of existing code then I would suggest that you rename all your *.cpp files to *.hpp (c++ header files) and then add suitable header guards. Furthermore a convenient way of handling this code of base is to create an additional header file config.hpp and include all your other headers in that file. Then in your main.c it is a simple matter of including the config.hpp file.
e.g.
// Config.hpp ------------------------------------------------=
#include "example.hpp"
#include "example1.hpp"
#include "example2.hpp"
// etc.
// main.cpp --------------------------------------------------=
#include "Config.hpp"
int main() {
// Your code here.
return 0;
}
Furthermore if you wanted to continue with your project structure it would be a simple matter of separating all your code into functions that needed to access arpackcpp directly. Then include them all into one *.cpp file, and compile into a *.o and link.

Related

precompiled header clang redefinition of error [duplicate]

I'm writing a library based on OpenVPN3, which is the C++ OpenVPN client implementation in header only, no cpp files. Therefore, I'm having to rely on having only one cpp file, which is the client itself, which includes a header that includes tons of other headers.
The problem is that, because of this, I cannot separate code into multiple cpp files. I'd like to be able for people to use my library, be it precompiled or compiled by them, but they cannot include the same headers on more than 1 cpp file or in the linking process there will be lots of redefinitions. There are also some static variables in the headers, for example.
If someone want to take a look at the number of things added into the 'master' header file: https://github.com/lucaszanella/libopenvpn3/blob/9b3440a736d90b671e9376d2d9e4911475e07112/src/OpenVPNClient.hpp
I know that there are some libraries like Asio that are also header-only and they're used without any problems by everyone.
Some techniques for not redefining a class or a function are to forward declare them but give no definition, but the problem here is that the person who's using my library is going to have to access its methods and everything. Is it possible to separate my methods from the ones used by my library on the headers?
you can put #pragma once on the most top of the file to avoid the same class clash due to being defined twice
If you do not want to duplicate import you can like tadman said:
at the top of the file
#ifndef HEADER
#define HEADER
//code goes here
#endif

How to avoid class/variable redefinition in C++ header only libraries

I'm writing a library based on OpenVPN3, which is the C++ OpenVPN client implementation in header only, no cpp files. Therefore, I'm having to rely on having only one cpp file, which is the client itself, which includes a header that includes tons of other headers.
The problem is that, because of this, I cannot separate code into multiple cpp files. I'd like to be able for people to use my library, be it precompiled or compiled by them, but they cannot include the same headers on more than 1 cpp file or in the linking process there will be lots of redefinitions. There are also some static variables in the headers, for example.
If someone want to take a look at the number of things added into the 'master' header file: https://github.com/lucaszanella/libopenvpn3/blob/9b3440a736d90b671e9376d2d9e4911475e07112/src/OpenVPNClient.hpp
I know that there are some libraries like Asio that are also header-only and they're used without any problems by everyone.
Some techniques for not redefining a class or a function are to forward declare them but give no definition, but the problem here is that the person who's using my library is going to have to access its methods and everything. Is it possible to separate my methods from the ones used by my library on the headers?
you can put #pragma once on the most top of the file to avoid the same class clash due to being defined twice
If you do not want to duplicate import you can like tadman said:
at the top of the file
#ifndef HEADER
#define HEADER
//code goes here
#endif

dealing with includes and using headers

I have "Hello World" code that uses function fhi from another hi.cpp file that has it's header.
Correct my if my understanding is wrong according following:
I can do include cpp file like #include "c:\c\hi.cpp" instead of using header without any problems except that fact that it looks more readable in header file.
If I include header like sample in my main program hi.h, must hi.h include hi.cpp, or it is done automatically according the same file name hi. I'm wondering how compiler knows where is function fhi body.
Is it possible to have different names for header and cpp files?
Programm:
#include "stdafx.h"
#include "c:\c\hi.h"
int _tmain(int argc, _TCHAR* argv[])
{
fhi(1);
return 0;
}
hi.h
#include <cstdlib>
#include <iostream>
int var;
int fhi(int f);
hi.cpp
#include <cstdlib>
#include <iostream>
int fhi(int f)
{
return 0;
}
must hi.h include hi.cpp
No. hi.h contains only declarations, that can be other by other .cpp files.
I'm wondering how compiler knows where is function fhi body.
It doesn't. You need to compile all *.cpp files into the object files. In your case, you will have two object files: program.o and hi.o. The linker can now take these two object files, and spit out the executable. References to other functions(in this case the actual definition of fhi(..)) is resolved in this stage.
Also why are you using absolute paths in #includes? It will break when you move the "c" directory around.
What normally happens is that the build system compiles the .cpp files into object files, that then are used to build the main executable. The means to tell this to the build system vary greatly.
One important point is that your hi.cpp must include hi.h. You should also put an include guard in hi.h, to make it safe to be included more than once in a translation unit.
I can do include cpp file like #include "c:\c\hi.cpp" instead of using
header without any problems except that fact that it looks more
readable in header file.
yes, you can do so but it is not recommended, one of the problems is encapsulation; you are not hiding implementation details. readability as you mention is also a concern, a header is easier to read since it clearly shows what methods are public.
If I include header like sample in my main program hi.h, must hi.h
include hi.cpp, or it is done automatically according the same file
name hi. I'm wondering how compiler knows where is function fhi body.
the header needs to be explicitly included in hi.cpp and any .cpp file that use the class defined in the header.
Is it possible to have different names for header and cpp files?
yes but it is not recommended, it makes it more difficult to find things.
as a general rule: think about that other programmers may want to look in your code so you need to structure it so that it is easy to read and understand as well as making it easier for you 2 years down the road to remember where things are.
In Visual Studio all CPP files included in the project will be compiled to produce OBJ files. These OBJ files will be linked together to form the EXE or DLL.
Including files are similar to pasting the contents of the file at that location. The only difference is that this pasting is done by the pre-compiler during compilation.
Finding out where a function body resides is done by the either the compiler if the function is inline or by the linker when the final binary is created.
First, if the header file is in the same directory as the source file including it, you can use just
#include "hi.h"
In other words, you don't have to use a full path. (See e.g. the inclusion of "stdafx.h".)
Second, in your header file you don't need to include other header files, unless you need types from those. In your header file you don't have anything that needed from the header files you include.
Third, you should protect header files header files from being included more than once in the same source file, this can be done with a so called include guard, on in some compiler via a special directive called #pragma once.
Fourth, in your header file you define a global variable var. This variable will then be defined in every source file you include the header file in, which will lead to errors. You need to declare the variable as extern:
extern int var;
Then in one source file you define the variable like you do now.
Fifth, you should never include source files in header file (with some special exceptions that you don't have to think about yet). Instead you add all source files to the project (I assume you are in MS VisualStudio) and it they will all be built and linked together automatically.
Sixth, since you seem to be using VisualC++, then you are probably using something called precompiled headers. This is something the compiler uses to speed up compilation. However, for this to work you have to include "stdafx.h" in all source files. That include actually has to be the first non-comment line in each source file.

Organize includes

Is there some preferred way to organize ones include directives?
Is it better to include the files you need in the .cpp file instead of the .h file? Are the translation units affected somehow?
How about if I need it in both the .h file and .cpp file, should I just include it in the .h file? Will it matter?
Is it a good practice to keep the already defined files in a precompiled header (stdafx.h), for instance std and third party libraries? How about my own files, should I include them in a stdafx.h file along the way as I create them?
// myClass.h
#include <string>
// ^-------- should I include it here? --------
class myClass{
myClass();
~myClass();
int calculation()
};
// myClass.cpp
#include "myClass.h"
#include <string>
// ^-------- or maybe here? --------
[..]
int myClass::calculation(){
std::string someString = "Hello World";
return someString.length();
}
// stdafx.h
#include <string.h>
// ^--------- or perhaps here, and then include stdafx.h everywhere? -------
You should have them at the top of the file, all in one place. This is what everyone expects. Also, it is useful to have them grouped, e.g. first all standard headers, then 3rd-party headers (grouped by library), then your own headers. Keep this order consistent throughout the project. It makes it easier to understand dependencies. As #James Kanze points out, it is also useful to put the header that declares the content first. This way you make sure that it works if included first (meaning it does no depend on any includes that it does not include itself).
Keep the scope as small as possible, so that a change in the header affects the least number of translation-units. This means, whenever possible include it in the cpp-file only. As #Pedro d'Aquino commented, you can reduce the number of includes in a header by using forward declarations whenever possible (basically whenever you only use references or pointers to a given type).
Both - explicit is better than implicit.
After some reading, I believe you should only include headers in the PCH if you are confident that they do not change anymore. This goes for all standard headers as well as (probably) third party libraries. For your own libraries, you be the judge.
This article on Header file include patterns should be helpful for you.
Is there some preferred way to organize ones include directives?
Yes, you can find them in the above article.
Is it better to include the files you need in the .cpp file instead of
the .h file? Are the translation units
affected somehow?
Yes, it is better to have them in .cpp. Even, if a defined type is required in definition of another type, you can use forward declaration.
How about if I need it in both the .h file and .cpp file, should I just
include it in the .h file? Will it
matter?
Only in .h file, but it is suggested to forward declare in header files, and include in .cpp files.
Is it a good practice to keep the already defined files in a precompiled
header (stdafx.h), for instance std
and third party libraries? How about
my own files, should I include them in
a stdafx.h file along the way as I
create them?
I personally have not used precompiled headers, but there has been a discussion on them on Stackoverflow earlier:
Precompiled Headers? Do we really need them
Is there some preferred way to organize ones include directives?
No common conventions. Some suggest alphabet-sorting them, I personally dislike it and prefer keeping them logically grouped.
Is it better to include the files you need in the .cpp file instead of the .h file?
In general, yes. It reduces the count of times that the compiler needs to open and read the header file just to see the include guards there. That may reduce overall compilation time.
Sometimes it's also recommended to forward-declare as much classes as possible in the headers and actually include them only in .cpp's, for the same reason. The "Qt people" do so, for example.
Are the translation units affected somehow?
In semantic sense, no.
How about if I need it in both the .h file and .cpp file, should I just include it in the .h file? Will it matter?
Just include it in the header.
Is it a good practice to keep the already defined files in a precompiled header (stdafx.h), for instance std and third party libraries? How about my own files, should I include them in a stdafx.h file along the way as I create them?
Precompiled headers can significantly reduce compilation times. For example: one of my projects that includes boost::spirit::qi compiles in 20 secs with PCH on, and 80 secs — without. In general, if you use some heavily template-stuffed library like boost, you'd want to utilise the advantage of PCH.
As for the question in your code sample: since you don't use std::string in the header, it's better to include it in the .cpp file. It's alright to #include <string> in stdafx.h too — but that will just add a little bit of complexity to your project and you'll hardly notice any compilation speed-up.
(4) I wouldn't recommend to include any additional files into stdafx.h. or similar "include_first.h" files. Direct including into cpp or particular h files allow you to express dependencies of your code explicitly and exclude redundant dependencies. It is especialy helpful when you decide to decompose monolithic code into a few libs or dll's. Personally, I use files like "include_first.h" (stdafx.h) for configuration purpose only (this file contains only macro definitions for current application configuration).
It is possible to provide precompiled headers for your own files by marking another file to stop precompilation instead of stdafx.h (for instance, you can use special empty file named like "stop_pch.h").
Note, precompiled headers may not work properly for some kinds of sofisticated usage of the preprocessor (particulary, for some technics used in BOOST_PP_* )
From the performance point of view:
Changing any of the headers included from stdafx.h will trigger a new precompilation, so it depends on how "frozen" the code is. External libraries are typical candidates for stdafx.h inclusion, but you can certainly include your own libraries as well - it's a tradeoff based on how often you expect to change them.
Also, with the Microsoft compiler you can put this at the top of each header file:
#pragma once
This allows the compiler to fully skip that file after the first occurrence, saving I/O operations. The traditional ifndef/define/endif pattern requires opening and parsing the file every time it's included, which of course takes some time. It can certainly accumulate and get noticeable!
(Make sure to leave the traditional guards in there, for portability.)
It might be important to notice that the order of classes in Translation Unit need to be correct or some c++ features are just disabled and results in a compile-time error.
Edit: Adding examples:
class A { };
class B { A a; }; // order of classes need to be correct

Is including C++ source files an approved method?

I have a large C++ file (SS.cpp) which I decided to split in smaller files so that I can navigate it without the need of aspirins. So I created
SS_main.cpp
SS_screen.cpp
SS_disk.cpp
SS_web.cpp
SS_functions.cpp
and cut-pasted all the functions from the initial SS.cpp file to them.
And finally I included them in the original file :
#include "SS_main.cpp"
#include "SS_screen.cpp"
#include "SS_disk.cpp"
#include "SS_web.cpp"
#include "SS_functions.cpp"
This situation remains for some months now , and these are the problems I've had :
The Entire Solution search (Shift-Ctrl-F in VS) does not search in the included files, because they are not listed as source files.
I had to manually indicate them for Subversion inclusion.
Do you believe that including source files in other sources is an accepted workaround when files go really big ? I should say that splitting the implemented class in smaller classes is not an option here.
There are times when it's okay to include an implementation file, but this doesn't sound like one of them. Usually this is only useful when dealing with certain auto-generated files, such as the output of the MIDL compiler. As a workaround for large files, no.
You should just add all of those source files to your project instead of #including them. There's nothing wrong with splitting a large class into multiple implementation files, but just add them to your project, including them like that doesn't make much sense.
--
Also, as an FYI, you can add files to your projects, and then instruct the compiler to ignore them. This way they're still searchable. To do this, add the file to the project, then right-click it, and go to Properties, and under "General" set "Exclude from Build" to Yes.
Don't include cpp files in other files. You don't have to define every class function in one file, you can spread them across multiple files. Just add them individually to the project and have it compile all of them separately.
You don't include implementation (.cpp) files. Create header files for these implementation files containing the function/class declarations and include these as required.
There are actually times you will want to include CPP files. There are several questions here about Unity Builds which discuss this very topic.
You need to learn about Separate compilation, linking, and what header files are for.
You need to create a header file for each of those modules (except possibly main.cpp). The header file will contain the declarative parts of each .cpp source file, and the .cpp files themselves will contain the instantive parts. Each unit can then be separately compiled and linked. For example:
main.cpp
#include "function.h"
int main()
{
func1() ;
}
function.h
#if !defined FUNCTION_H
#define FUNCTION_H
extern void func1() ;
#endif
function.cpp
void func1()
{
// do stuff
}
Then function.cpp and main.cpp are separately compiled (by adding them to the sources for the project), and then linked. The header file is necessary so that the compiler is made aware of the interface to func1() without seeing the complete definition. The header should be added to the project headers, then you will find that the source browser and auto-completion etc. work correctly.
What bothers me with this question is the context of it.
A large cpp file has been created, large enough to warrant thinking about splitting it into smaller more manageable files. The proposed split is:
SS_main.cpp
SS_screen.cpp
SS_disk.cpp
SS_web.cpp
SS_functions.cpp
This seems to indicate that there are separate units of functionality from a specification and design perspective. We can only guess at the coupling between these units of code.
However, it would be a start to define these code units such that each new cpp file has its own header file thus defining the interfaces of these units and the (low) coupling between them to achieve (high) cohesion for each unit.
We are refactoring here.
It is not acceptable to use included cpp files in this context it as does not provide any advantages. The only time I've come across included cpp files is when a one is included to provide code for debug code, and example being to compile non-inline versions of functions. It helps in stepping through code in the debugger.