Compiling at runtime and #include custom header in C++ - c++

I need to compile and link some code at runtime. I am using the approach suggested here: https://stackoverflow.com/a/10565120/3038460
Basically I am writing my code into a .cpp file and then compiling with
/usr/bin/g++ -shared mysource.cpp -o libname.so
Everything works fine while I only #include headers from standard libraries. But what if I need to use a custom class within the 'dynamic' code? How can include my own header? The .cpp file is temporary stored in the same location of my binary file and this might be different than the location of my source files. Is there a way to know at runtime where the original source code was located? I doubt.
Moreover I would like my code to work even if the original source code is not available.
To clarify, mysource.cpp might look like this:
#include <stdlib.h>
#include <vector>
#include "myheader.h" <---- how can g++ find this file? At runtime,
when I create mysource.cpp, I have no idea
where myheader.h is located
void f(){
// Code
}
What's the best solution to solve this problem?

Generate the contents of that header file into the generated source file.
Technically, an #include directive is just a directive to include the full contents of a header file in the body of a source file (specifically, at the point where you included it) at compile time. You can thus skip the middleman and generate the contents of that header file into your source file before compiling it instead of an #include

Related

C++ Using MACRO without INCLUDE statement

In DirectX Graphics Samples MiniEngine sample, there is an "inline" source file Functions.inl that uses a macro INLINE that is defined in a header in same folder, Common.h .
What mechanism/declaration permits Functions.inl to use INLINE without an #include "Common.h" statement?
My specific issue is that I have created a VS2019 UWP C++ project, and I am importing a subset of this source and cannot compile the copy of Functions.inl without modifying and adding an #include statement.
"Math/Functions.inl" is not a source file. It is not compiled individually. It appears to be included, just like a header is. Let's take a look at how it is used:
// Core/VectorMath.h
#pragma once
#include "Math/Scalar.h"
...
#include "Math/Functions.inl"
Unlike a header, it is not included into the top of the file, but the bottom. So, I guess it could be called a footer. As you may notice, there are headers included before it. Let's take a look inside one:
// Math/Scalar.h
#pragma once
#include "Common.h"
...
Ah. So, "Common.h" is included before "Math/Functions.inl". That is why "Math/Functions.inl" can use INLINE when included into "Core/VectorMath.h".
Essentially, the file depends on a macro without including it directly and thereby it has an invisible dependency to have that header included before it.
This a bad practice in case of header files which are intended to be included by the user of the library. But this file is presumably intended to not be included except through "Core/VectorMath.h", so the the invisible dependency can even be seen as advantageous. Nevertheless, many IDEs / static code analysers will fail to analyse the file correctly, so I would personally still avoid this practice.
The *.inl extension is usually used to indicate that the file is an inline-definition of something defined in a header. Effectively, the *.inl file is generally treated as an inline-equivalent to a *.cpp file.
In the same way that *.cpp files can use symbols #included in the header for that *.cpp file, *.inl files usually have the same assumption.
In this specific example. it appears that Functions.inl is included after a bunch of other headers are included
#include "Math/Scalar.h"
#include "Math/Vector.h"
#include "Math/Quaternion.h"
#include "Math/Matrix3.h"
#include "Math/Transform.h"
#include "Math/Matrix4.h"
#include "Math/Functions.inl"
Which likely transitively pick up the INLINE macro

Header files not found even though they are in the right directory?

I'm fairly new to programming using linux so forgive me for any dumb errors I might make in my question but basically I am trying to compile using the terminal (C++) and my code in a .txt file however I keep getting a fatal error that my header file can't be found? When I try to type
g++ -o test main.cpp header.h
I get the error stating "header.h: no such file or directory" in the terminal. I've ensured that both the cpp and header files are in the same directory but no luck there. I've also used
#include <"header.h">
in my main.cpp and header file to try different fixes. I've researched and looked at different answers but no fixes either. Any suggestions?
#include <"header.h">
Use either
#include <header.h>
will lookup the standard include directories for these header files first
or
#include "header.h"
will lookup all include directory pathes specified with the preprocessor options
but don't mix these up.
Also you don't need to specify the header in the compiler command line
g++ -o test main.cpp header.h
# ^^^^^^^^ omit this
That's what the #include statement in your code is for.

Get all include files of a cpp file considering preprocessor defines (fast)

I need a tool (command line, script or source code) that extracts all inlcude files that are included by a source file (recursive) with given preprocessor defines and include paths. I want to know the ones that could be found and the one that doesn't. The include files that could be found shall be recursivly parsed.
I know about the
gcc -M /-MM
cl /P
solution, but this does not work for me. The preprocessor stops as soon as it could not open a file. But at this time I don't have the correct path for that files and just want the preprocessor to skip that file and to tell me that it could not include that file
Also the cinclude2dot.pl from here is not useful, because it seems not to consider given preprocessor defines.
Very useful is the include file hierarchy finder from CodeProject. It considers the preprocessor flags and shows me all include files. Even the includes that couldn't be opened. But it is written in MFC and I would have to reimplement this for the gcc what is not such simple because a lot of WinAPI stuff is used even inside the parser.
Thus, maybe some one knows another solution.
an simple example:
main.cpp
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <SharedClass.h>
#include "MyClass.h"
#ifdef FOO
#include <OptClass.h>
#endif
int main() {}
Right now I start the include extraction like (simplified):
.getAllIncludes main.cpp -I includepath1;includepath2 -PD FOO
and obtain:
cannot open //-> I don't care right now, it's a default header
cannot open // -> here I can extract the info that I need boost
SharedClass.h
SharedDependenyClass.h //a header that is included by SharedClass...
MyClass.h
TestClass.h //a header that is included by the MyClass header...
TestClass2.h //a header that is included by the TestClass header...
OptClass.h
and for
.getAllIncludes main.cpp -I includepath1;includepath2
I'll obtain:
cannot open //-> I don't care right now, it's a default header
cannot open // -> here I can extract the info that I need boost
SharedClass.h
SharedDependenyClass.h //a header that is included by SharedClass...
MyClass.h
TestClass.h //a header that is included by the MyClass header...
TestClass2.h //a header that is included by the TestClass header...
I know that the deafault header may also define some values. But in my case I don't need that information, because the project source code doesn't depend on any of that defines. If thus, I feed my tool with this preprocessor define...
In the end the tool works quite well. It runs recursivly over ALL necessary files and in the end I have all needed files for the project. Of course there are some small restrictions I don't want to name then all (e.g. every header of an source file name has the same name, ... ).
Using gcc -M <source_file>, the code is not compiled, it is only processed by the precompiler. And, any solution you may find needs to process the source using the precompiler, to be correct. Imagine that the source, somewhere, has the following snipset:
#ifdef USE_BOOST_SUPERLIB
# include <boost/superlib.hpp>
#endif
then without preprocessing you cannot know if <boost/superlib.hpp> is included.

Why don't I need to include library.cpp in the header?

I have a question about libraries. When I write a library I have 2 files: library.h and library.cpp.
The first one contains the prototypes of the functions and the second one contains the definitions. Well, in library.cpp I include #include "library.h", so they are connected in one way, but what happens with the header? Why don't I have to write #include "library.cpp" in the header?
When I use the library in the main file, I write #include "library.h", which includes the prototypes, but how does the compiler know where the definitions are?
Explained briefly:
(1) Your library.cpp file is sent to the preprocessor.
(2) The preprocessor reads the line #include "library.h" and goes and finds the file library.h.
(3) The contents of library.h are literally copied into the library.cpp file.
(4) The library.cpp file is compiled and linked with the main file.
Thus, all of the "prototypes" in the header are copied into the top of the implementation file. .cpp files are compiled and linked. The header files themselves are not compiled -- their contents are copied into the .cpp files.
There is a tool called linker which is responsible for link your generated object files. You should look for compilation process to understand it better.
The preprocessor pulls the header file into the CPP file, so the compiler sees the prototypes and the definitions together.
If you were to pull the CPP file into the header file, you would either send the preprocessor into an infinite loop, or by using
#ifndef __FOOBAR__
#define __FOOBAR__
(code file)
#endif
around the header AND source files you would read the file just once.
All the cpp files are compiled seperately and the code is accumulated in a big pile somewhere. The linker collects all the symbols in your code and assigns them an address within this pile. So although your file doesn't see library.cpp directly, it knows the symbols from library.h and the assigned addresses. It can then zoom directly to the required code in the big pile. Not the most technical answer I know..
It was my understanding that when you type #include "library.h" in your code the compiler is set to also load library.cpp. I was taught in school that there isn't really any way to break this connection unless you were to manually compile and link each file either using compiler commands or a makefile appropriate for the system you're using (Windows, *nix, MacOS, etc.)
You have to type #include "library.h" in the library.cpp file because that is where the function prototypes are stored. You can "cheat" and put the function prototypes in the .cpp file and just type #include "library.cpp" but this is bad practice and is generally discouraged in the programming community.

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.