I'm building an evolution simulator in C++, but not as a "real" runnable program, but rather a class that other programs should #include
. This class, called World
, has some functions such as update()
, getInfo()
, etc...
I'm facing two problems here. First off, I don't know how exactly should I compile the class, and which files should I provide the user program (the one that #include
s the class) with. Obviously, the program should receive the .hpp
file, but what else? An object file of the class World
? That would imply that I'd need to compile the user program with the g++ World.o user.o -o user
syntax, but is there a way to avoid doing that (mentioning World.o
in my compile commands)? The same way I don't need to include iostream.o
in the compile command.
The second problem is that the World
class #include
s some other classes, such as Organism
, which, in turn, has to include the Block
class in order to inherit from it. How can I compile this code in order to get a single World.o
file (if that is the answer to problem 1)?
To me that sounds like you want to make a library out of your World
class. A library usually provides a bunch of types or functions or variables to be linked to/used by executables or other libraries.
A library is typically made up by the public interface and the rest (internals, implementation details). The former goes into the library header file, the ladder into other headers or implementation files.
The interface definition contains everything a potential user of the library needs to work with. No more, no less. That is,
If the user only needs to interact with the World
but not with any Organism
, this class goes not into the library header but, for example only included into the relevant implementation files. The implementation itself may be split into different files. It's up to the linker to combine these appropriately.
Defining the build configuration manually can be quite a hassle when lots of files and libraries are involved. Good thing, there are tools to generate this automatically. For example cmake. An example cmake configuration file could look like this:
# CMakeLists.txt
# add a shared library to build configuration
add_library(my_library_name SHARED my_library_file1.cpp my_library_file2.cpp)
# add an executable to build configuration
add_executable(my_executable_name executable_file1.cpp executable_file2.cpp)
# link the library to the executable
target_link_libraries(my_executable_name my_library_name)
just run cmake
with the path to the directory where the CMakeLists.txt
is located to build the necessary makefiles, then run make
, then you should be done.
See also:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With