How to include header files with similar names in C++ project - c++

I am using an external library in my C++ program. This library has a fie named "Common.h". Without knowing about this file, I also created a "Common.h" in my program. Using the compiler flag "#pragma once" in the headers I could ensure that both the files can be included in the compilation. However, I realized that when I call my "Common.h" in my program, the preprocessor wrongly includes the "Common.h" from the external library which breaks the compilation. Is there any option like "namespace" which allows me to include the correct file. I find it really difficult, as we may not (indeed need not) aware about all the files in the external library.

Usually program has several so called include paths to look for header files. It seems you have included both path to directory containing your "Common.h" file, as well as library headers directory. As for me, perfect solution seems to remove include path of library files and use explicit relative path, as:
#include "mylib/include/Common.h"

You can simply rename your "common.h" file and then include that

Related

CMake add_executable() use .cpp file or .hpp file?

I've read a bunch questions on this site about the usage of add_executable function in CMake, but have not found an exact answer to my confusion.
My question is why we only add .cpp files in the add_executable function but not .hpp files?
I understand header files are like "indices" for functions and classes in the corresponding .cpp files. But if we don't include them in the add_executable function, how are they used in the build process?
For example, will the A.hpp file be used when another source file import A.hpp? But then A.hpp is not in the add_executable function... How does the program know where to find A.hpp?
Thanks!
Header files, which often have .h or .hpp extension, although not always - for example, C++ standard library headers have no extensions - are "copy-pasted" by compiler into every .cpp (or .C, or .cc) which has #include directive to include the file.
Because of that, build system, such as CMake, doesn't have to know about them when the final executable is built - their contents is already accounted for by literal inclusion of their code into .cpp file.
However, build systems need to know about those files when dependencies are specified - to ensure that the whole application is rebuilt whenever any of those files is updated, and also to provide the proper inclusion path to the compilation command.

static assert if a header is included in another header but not a cpp

I have a c++ library which uses some functions from windows.h, and there is a utility header which defines conversions for some weird windows types into standard c++.
I'm wondering if there is a way to assert if the utilities are included into another header. The idea is to only include the utilities into .cpp files so that we don't taint the rest of the codebase with windows.h and windows types and the problems associated with including that (min/max, etc).
Check if the header guard of windows.h is defined with an #ifdef block.
#ifdef _WINDOWS_
static_assert(false, "Don't include windows.h in header files!");
#endif
If it's included in another header, that's because a cpp file is including it somewhere. So every code end up in a cpp file eventually.
You may want to look into module ts, which had not the transitive nature of headers, and any importing code won't import your module's imports.
If you can't use modules and still want to encapsulate headers by only allowing it in some places, you could place that header in a special directory, then only add that include directory on some allowed targets. If any other "disallowed" targets which don't have that include directory tries to include it, then a compilation error will occur.
Note that all cpp files that don't have that include directory will fail to include the header. But it's an advantage rather than an inconvenient: you will have to explicitly add it to your build system, making easy to spot such code.
Here's the directory structure:
- src/
a.cpp
b.cpp
- include/
- private-header/
- windows/
windows-conversion.h
Here's an example with CMake:
add_library(using-windows-headers INTERFACE)
target_include_directory(using-windows-headers INTERFACE include/private-header/windows)
Then, on a per-target basis, you can link the target:
target_link_libraries(some-module PRIVATE using-windows-headers)
Be aware that this will work only if you put PRIVATE there, so any other dependent targets won't have the include directory.

"multiple definition of ..." using arpackpp

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.

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.

dealing with stdafx.h when have separate directory library

I have library that consist of many directories each of them contains libX.cpp and libX.h files where X is directory name. One libX might be used in different projects. Problem is that while compiling each project asks include stdafx.h in libX.cpp. I suppose I must include stdafx.h file that was generated for current project (correct me if I'm wrong). Ok, I'm writing #include "some_absolute_path1\stdafx.h" in for example libA.cpp file.
But I'm using the same libA.cpp in another project and then I must change line
#include "some_absolute_path1\stdafx.h"
to
#include "some_absolute_path2\stdafx.h"
It is not very comfortable to change stdafx.h path while switching between projects.
What is best way to deal in that situation?
You can simply not use stdafx.h. It is only used for precompiled headers.
You can do #include "some_absolute_path2\libX.h"
If you still want to use precompiled headers you just #include "some_absolute_path2\libX.h" in the stdafx.h of the project that needs the library.
Any include is required when your lib is using some of the resources defined in that file to be included. If you need to include stdafx.h is because you have some dependency that is forcing that. You should review what causes you to require this project related file to be included in your libraries (not specific of the project)
I found this article: http://en.wikipedia.org/wiki/Precompiled_header
I then would try to move stdafx.h to be the first include in your main.cpp where you also include your libx.h files.