So recently I've been trying out autotools to build a C++ Library. Originally I was just working on pure custom classes, which is quite easy to just #include and then compile with g++. But when I want to write some custom functions for the library, I've learnt that it's a bad practice to write functions within header file, but rather I should declare it in header then wrote it in a separate .cpp file. Which later I've tried and successfully compiled with g++ ./lib/**/*.cpp src/main.cpp.
So basically my project structure is that codes are put under src/, headers are under include/ and functions are put under lib/. And following is my src/Makefile.am
AUTOMAKE_OPTIONS = subdir-objects foreign
bin_PROGRAMS = main
include_HEADERS = -I../include/**/*.hpp
main_SOURCES = -I../lib/**/*.cpp main.cpp
And for the endpoints' directory (under lib/) I have something like following
main_SOURCES = stdout.cpp
But it gave me error that no program named main, so I figured maybe all those function files has to be compiled first, so I changed them into
noinst_PROGRAMS = stdout
stdout_SOURCES = stdout.cpp
But then they gave me the following error
/usr/sbin/ld: /usr/lib/gcc/x86_64-pc-linux-gnu/11.1.0/../../../../lib/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status
I know that the error meant that there's no main() written in the file, but since it's a library function file, it doesn't meant to have a main(), it's meant to be called by other file (like main.cpp). And to here I'm stuck.
I've tried to find documentation online, but it seems that most of them are targeted at C programs instead of C++, which I'm not sure if those steps are compatible. And I remember C++ libraries are compiled into .so or .o file while most tutorials seems to be using .la files.
MWE
src/main.cpp
#include"../include/conn/bash/stdout.hpp"
#include<string>
#include<iostream>
int main() {
std::string o=d::conn::bash::exec("ls");
std::cout << o << std::endl;
return 0;
}
include/conn/bash/stdout.hpp
#ifndef __CONN_BASH_O__
#define __CONN_BASH_O__
#include<string>
namespace d { namespace conn { namespace bash {
std::string exec(const char*);
}}}
#endif
lib/conn/bash/stdout.cpp
#include"../../../include/conn/bash/stdout.hpp"
#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
std::string d::conn::bash::exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
// https://stackoverflow.com/a/478960/8460574
Compiled and tested with g++ ./lib/**/*.cpp src/main.cpp
I've tried to find documentation online, but it seems that most of
them are targeted at C programs instead of C++,
"Most of them" suggests that you are searching out tutorials. Documentation would be the Automake manual, which you would be well advised to read. It covers these topics and many more that you will want to know about as you continue with the Autotools, and with Automake in particular. At minimum, you should know how to find the manual so as to consult it at need. Tutorials and guides can be helpful, but they should be regarded as supplements to the manual, not primary sources.
which I'm not sure if
those steps are compatible.
They mostly are. The main thing to be aware of is that command-line options for the C compiler are specified via a CFLAGS primary (see below), whereas those for the C++ compiler are specified via a CXXFLAGS primary.
And I remember C++ libraries are compiled
into .so or .o file while most tutorials seems to be using .la files.
You seem to be confused. The formats associated with those extensions are not language-specific, and .o does not designate a library at all.
.o is the conventional extension for the object file arising from compiling a single source file. These can be linked into an executable, or they can be gathered together into a library, but they are not libraries themselves.
Conventional UNIX library extensions are .a for static libraries and .so for shared libraries. This applies to any language that can be used to build general-purpose link libraries, including C, C++, Fortran, and a variety of others.
The .la extension is something else. It designates a libtool library. Libtool is another of the autotools, focused on abstracting system-specific details of building and using libraries. This is again language independent. Building a libtool library will cause either a corresponding static library, a corresponding shared library, or both to be built and installed, depending the options specified in the Autotooling and / or on the configure command line.
You should use libtool if you are building shared libraries with the Autotools. You may also use it if you are building only static libraries (.a), but it is a bit simpler in that case to leave libtool out of the picture.
As for the specific question posed, you write:
And for the endpoints' directory (under lib/) I have something like
following
main_SOURCES = stdout.cpp
But it gave me error that no program named main,
Always present the actual text of the error message (as text), rather than a paraphrase. If you have to ask a question about it here, then there is a significant risk that your understanding of the message is incomplete or wrong, and therefore that your paraphrase is misleading.
In this case, I am relatively confident that Automake's complaint was that there is no target named "main". The line you've given specifies a source list for such a target, but Automake does not find that target defined in that Makefile.am file. The difference between "program" and "target" is a bit subtle, but significant.
Supposing that you are trying to build a convenience library -- that is, one that groups functions for compile-time use in building other targets, but is not intended to be installed as a standalone library* -- you could get it with something like:
noinst_LIBRARIES = libendpoints.a
That consists of thee main pieces:
LIBRARIES is the "primary", specifying what kind of definition is being given. In this case, it is the definition of a list of static library targets included in the project.
libendpoints.a specifies the name of a (static library) target. This is an external name: the build will generate a file by this name in the build tree. Do make a habit of using standard naming conventions for this, such as I demonstrate.
noinst specifies where the built target will be installed by make install. This particular value is a special one indicating that the target will not be installed at all. If you wanted it installed in the configured libdir then you would instead say lib.
The properties of that target must be given by other definitions, based on a munged form of its name. For instance, its source list might look like this:
libendpoints_a_SOURCES = stdout.cpp
That again consists of three pieces:
SOURCES is again the primary. In this case, it says that the definition provides a source list for some target.
libendpoints_a identifies the target whose source list is being given. It is a munged form of the target name, with characters that cannot appear in variable names replaced by '_' characters.
stdout.cpp is the (single-element) source list.
To use that, the main program's properties would also need to specify that the library should be linked. That would mean something along these lines in the Makefile.am in which the main program target is defined:
main_LDADD = lib/endpoints/libendpoints.a
That is again a three-part definition, whose interpretation I leave as an exercise.
*And if you wanted a static library that does get installed to the system then you would swap out the "noinst" for a prefix that identifies the installation location, such as "lib". And there is a slightly different form for libtool-mediated libraries, including shared libaries.
If you're just defining a convenience target for you library, you should be able to do so by declaring it as noinst_LIBRARIES = libmine.a and then declaring it as a stdout_LIBADD.
But most likely, if you don't want this as an installed library, you just want to list the sources directly in a single, non-recursive Makefile.am file, see https://autotools.io/automake/nonrecursive.html
If you do want your library to be installable, then you want to use libtool: https://autotools.io/libtool/index.html
Related
I've been recently reading about static and dynamic linking and I understood the differences and how to create static and dynamic library and link it to my project
But, a question came to my mind that I couldn't answer or find answer for it as It's a specific question ... when I compile my code on linux using the line
#include <stdio.h>
int main()
{
printf("hello, world!\n");
}
compiling using this command
[root#host ~]# gcc helloworld.c -o helloworld
which type of linking is this??
so the stdio.h is statically or dynamically linked to my project???
Libraries are mostly used as shared resources so, that several different programs can reuse the same pre-compiled code in some manner. Some libraries come as standard libraries which are delivered with the operating system and/or the compiler package. Some libraries come with other third party projects.
When you run just gcc in the manner of your example, you really run a compiler driver which provides you with few compilation-related functions, calling different parts of the compilation process and finally linking your application with a few standard libraries. The type of the libraries is chosen based on the qualifiers you provide. By default it will try to find dynamic (shared) libraries and if missing will attempt for static. Unless you tell it to use static libs only (-static).
When you link to project libraries you tell the gcc/g++ which libraries to use in a manner (-lname). In such a way it will do the same as with the standard libraries, looking for '.so' first and '.a' second, unless -static is used. You can directly specify the path to the full library name as well, actually telling it which library to use. There are several other qualifiers which control the linking process, please look man for 'g++' and 'ld'.
A library must contain real program code and data. The way it is linked to the main executable (and other libraries) is through symbol tables which are parts of the libraries. A symbol table contains entries for global functions an data.
There is a slight difference in the structure of the shared and static libs. The former one is actually a pre-linked object, similar to an executable image with some extra info related to the symbols and relocation (such a library can be loaded at any address in the memory and still should work correctly). The static library is actually an archive of '.o' files, ready for a full-blown linking.
The usual steps to create a library is to compile multiple parts of your program into '.o' files which in turn could be linked in a shared library by 'ld' (or g++) or archived in .a with 'ar'. Afterwards you can use them for linking in a manner described above.
An object file (.o) is created one per a .cpp source file. The source file contains code and can include any number of header files, as 'stdio.h' in your case (or cstdio) or whatever. These files become a part of the source which is insured by the cpp preprocessor. The latter takes care of macros and flattening all the #include hierarchies so that the compiler sees only a single text stream which it converts into '.o'. In general header files should not contain executable code, but declarations and macros, though it is not always true. But it does not matter since they become welded with the main source file.
Hope this would explain it.
which type of linking is this?? so the stdio.h is statically or
dynamically linked to my project???
stdio.h is not linked, it is a header file, and contains code / text, no compiled objects.
The normal link process prefers the '.so' library over the '.a' archive when both are found in the same directory. Your simple command is linking with the .so (if that is in the correct path) or the .a (if that is found in a path with no .so equivalent).
To achieve static linking, you have several choices, including
1) copy the '.a' archive to a directory you create, then specify that
directory (-L)
2) specify the path to the '.a' in the build command. Boost example:
$(CC) $(CC_FLAGS) $< /usr/local/lib/libboost_chrono.a -o $# $(LIB_DIRs) $(LIB_NMs)
I have used both techniques, I find the first easier.
Note that archive code might refer to symbols in another archive. You can command the linker to search a library multiple times.
If you let the build link with the .so, this does not pull in a copy of the entire .so into the build. Instead, the .so (the entire lib) is loaded into memory (if not already there) at run-time, after the program starts. For most applications, this is considered a 'small' start-up performance hit as the program adjusts its memory map (auto-magically behind the scenes) Note that the app itself can control when to load the .so, called dynamic library.
Unrelated:
// If your C++ 'Hello World' has no class ... why bother?
#include <iostream>
class Hello_t {
public:
Hello_t() { std::cout << "\n Hello" << std::flush; }
~Hello_t() { std::cout << "World!" << std::endl; }
void operator() () { std::cout << " C++ "; }
};
int main(int, char**) { Hello_t()(); }
I just started to learn C/C++, but I'm a bit confused. I often see the #include preprocessor directive, with a header file argument:
#include <stdio.h>
#include <iostream.h>
#include "windows.h"
#include <math.h>
But sometimes the .h is missing:
#include <iostream>
I already know, that the header file contains the signatures of the functions only, and some preprocessor commands. But when and how does the compiler include the math functions, if I include math.h?
If I create a library, then where to put the .c/.cpp/.h files, and how to include them?
When you install the compiler, the standard header and library files are also installed into well-known locations. For example, on a Linux or Unix system, the standard headers are typically installed under /usr/include or /usr/local/include and the standard libraries are typically installed under /usr/lib or /usr/local/lib.
When you #include the header file, the compiler will look for it in different places depending on whether you use the angle brackets (#include <stdio.h>) or quotes (#include "myfile.h"). For example, if you include a header file in angle brackets, gcc will search for that header in the following directories:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
If you include a header file with quotes, gcc will first search the current working directory, then additional directories as specified by command-line options, and finally the standard include paths above.
Most compilers allow you to specify additional include paths as arguments to compile command, such as
gcc -o executable-name -I /additional/include/path source-files
But sometimes the .h is missing:
#include <iostream>
This is the C++ convention1; C++ standard headers do not have the .h extension, I guess to make it look more object-oriented than it really is (that is, you can pretend you're importing the class directly, rather than including the text of the file that describes the class).
I already know, that the header file contains the signatures of the functions only, and some preprocessor commands. But when and how does the compiler include the math functions, if I include math.h?
The implementations of the math functions are typically kept in a separate library (code that's already been compiled and archived into a single binary file); depending on the compiler, the math library may or may not be automatically linked into the executable. For example, gcc does not automatically link in any math library functions, even if you include the math.h header file. You have to explicitly include the math library as part of the build command:
gcc -o executable-name command-line-options source-files -lm
With gcc, the convention is that -lname links in a library named libname.a2. The standard math library file is named libm.a, so -lm tells gcc to link in the machine code that's contained within libm.a.
Like the standard headers, the compiler will search for the standard libraries in well-known locations. You can specify additional search paths for libraries that aren't part of the standard installation, like so:
gcc -o executable-name command-line-options source-files -L /additional/library/path -ladditional-library
If I create a library, then where to put the .c/.cpp/.h files, and how to include them?
You can put the files pretty much anywhere you want; you'll specify where they are as part of the build command. So, say you're creating a new library named mylib. You create a new directory under your home directory:
mkdir ~/mylib
cd ~/mylib
Then you create and edit your source files and headers:
cd ~/mylib
vi mylib.h
vi mylib.c
To build mylib as a static library, do the following:
cd ~/mylib
gcc -c mylib.c
ar libmylib.a mylib.o
So when you're done, the directory ~/mylib contains the following:
libmylib.a
mylib.c
mylib.h
mylib.o
To use the functions collected in mylib in a program, you'd specify the header and library include paths as part of the compile command:
gcc -o executable-name command-line-options source-files -I ~/mylib -L ~/mylib -lmylib
So, if you include "mylib.h" in another program, this will tell the compiler to search for that header in ~/mylib, and it will tell the linker that the libmylib.a library will be found under ~/mylib.
In a real-world situation you'd handle all of the builds with makefiles instead of building everything by hand. You'd also probably set it up so that as part of the build process, all the headers that anyone else would need to use your library would be copied to a separate include subdirectory, and the library would be written to a separate lib subdirectory, so you could distribute your library without exposing your source code. In that case, the build command above would look more like:
gcc -o executable-name command-line-options source-files -I ~/mylib/include -L ~/mylib/lib -lmylib
1. This hasn't always been the case; the earliest implementations of C++ used iostream.h, vector.h, etc. I'm not sure exactly when that convention changed, but it's been a while.
2. Actually, I'm not sure anymore if this is a gcc convention or a *nix convention; the two have been joined at the hip for so long it's hard to remember sometimes.
Actually, the compiler doesn't know anything about other source files, it only knows about the current translation unit. It's the job of the linker to take all translation units and link them together with the libraries to create the executable program, and it's the linker that will resolve all definitions and that notice missing function definitions.
Traditionally, working with C or C++ is a four step process:
Edit files
Compile source files into object files
Link object files and libraries to generate the executable program
Run the program.
The preprocessor is usually built into the compiler, so preprocessing and compiling is only a single step.
As for the "missing" .h, none of the C++-only standard library header files have that extension.
Standard Template Library headers, such as < algorithm > include source code for the template functions, which get instantiated at compile time, based on the template type(s) involved in source code calls to template functions.
A library is a collection of object files in a single library file. The linker normally only includes the object files needed to satisfy the references to functions or data to build the program, not the entire library file. The exception to this is a dynamic link library, since all of that library will be loaded (if not already loaded) at program load time.
The compiler has default locations for headers using < > and using " ". The headers using " ", can include relative or absolute paths. The relative path may vary depending on the tool set.
Re
” How a compiler knows from a header file, that a source file exists somewhere?
Generally, how a compiler locates header files, or if they are files, depends on the compiler.
But usually one or more of the following mechanisms are used:
The compiler knows its own program location, and can look for include directories for standard headers, relative to that location. g++ does this.
The compiler can be configured with paths to include directories in one or more environment variables. E.g. g++ uses CPATH (among others), and Visual C++ uses INCLUDE (and possibly more).
The compiler can accept include directory paths as command line options. Typically this is -I or with Visual C++, alternatively /I.
The compiler can be configured via a configuration file in a well known location. For example, g++ uses a specs file.
The compiler can accept one or more configuration files as command line options. E.g. Visual C++ accepts so called "response files", and g++ accepts specs files, although with slightly different semantics than the general configuration specs file.
Possibly there are more mechanisms in use, but the above are the most common ones.
Re
” But when and how does the compiler include the math functions, if I include math.h?
It doesn't.
The whole of the standard library is linked in regardless of what headers you include. Depending on the quality of the implementation the unused parts of the standard library are then discarded.
When you use a 3rd party library you will generally have to explicitly link with that library, in addition to including one or more of its headers. The Visual C++ compiler supports #pragma directives that can be placed in headers and serve to automatically direct the linker. But this is not standardized, and e.g. g++ does not support that automagic mechanism.
Re
” If I create a library, then where to put the .c/.cpp/.h files, and how to include them?
Essentially you have free reins, you can do it any way you want. Which is problematic because users of a C++ library have to deal with different conventions and tools for each library, to the extent of using a different OS to "configure" things. However, nowadays it's popular to employ CMake for libraries with separate compilation, which helps to reduce the DIY problems.
A nice alternative is to create a header only library, with all the code in headers. Large parts of Boost are header only. The advantage is that it's very easy to use, no configuration or toolset adaption or whatever, but with currently popular 1950's build technology it can cause longer build times.
i want to know that in a c++ code during execution how iostream file is founded. we write #include in c++ program and i know about #include which is a preprocessor directive
to load files and is a file name but i don't know that how that file is located.
i have some questions in my mind...
Is Standard library present in compiler which we are using?
Is that file is present in standard library or in our computer?
Can we give directory path to locate the file through c++ code if yes then how?
You seem to be confused about the compilation and execution model of C++. C++ is generally not interpreted (though it could) but instead a native binary is produced during the compilation phase, which is then executed... So let's take a detour.
In order to go from a handful of text files to a program being executed, there are several steps:
compilation
link
load
execution proper
I will only describe what traditional compilers do (such as gcc or clang), potential variations will be indicated later on.
Compiling
During compilation, each source file (generally .cpp or .cxx though the compiler could care less) is processed to produced an object file (generally .o on Linux):
The source file is preprocessed: this means resolving the #include (copy/pasting the included file in the current file), navigating the #if and #else to remove unneeded sources and expanding macros.
The preprocessed file is fed to the compiler which will produce native code for each function, static or global variable, etc... the format depends on the target system in general
The compiler outputs the object file (it's a binary format, in general)
Linking
In this phase, multiple object files are assembled together into a library or an executable. In the case of a static library or a statically-linked executable, the libraries it depend on are also assembled in the produced file.
Traditionally, the linker job is relatively simple: it just concatenates all object files, which already contain the binary format the target machine can execute. However it often actually does more: in C and C++ inline functions are duplicated across object files, so the linker need to keep only one of the definitions, for example.
At this point, the program is "compiled", and we live the realm of the compiler.
Loading
When you ask to execute a program, the OS will load its code into memory (thanks to a loader) and execute it.
In the case of a statically linked executable, this is easy: it's just a single big blob of code that need be loaded. In the case of a dynamically linked executable, it implies finding the dependencies and "resolving the symbols", I'll describe this below:
First of all, your dynamically linked executable and libraries have a section describing which other libraries they depend on. They only have the name of the library, not its exact location, so the loader will search among a list of paths (LD_LIBRARY_PATH for example on Linux) for the libraries and actually load them.
When loading a library, the loader will perform replacements. Your executable had placeholders saying "Here should be the address of the printf function", and the loader will replace that placeholder with the actual address.
Once everything is loaded properly, all symbols should be resolved. If some symbols are missing, ie the code for them is not found in either the present library or any of its dependencies, then you generally get an error (either immediately, or only when the symbol is actually needed if you use lazy loading).
Executing
The code (assembler instruction in binary format) is now executed. In C++, this starts with building the global and static objects (at file scope, not function-static), and then goes on to calling your main function.
Caveats: this is a simplified view, nowadays Link-Time Optimizations mean that the linker will do more and more, the loader could actually perform optimizations too and as mentioned, using lazy loading, the loader might be invoked after the execution started... still, you've got to start somewhere, don't you ?
So, what does it mean about your question ?
The #include <iostream> in your source code is a pre-processor directive. It is thus fully resolved early in the compilation phase, and only depends on finding the appropriate header (no library code is actually needed yet). Note: a compiler would be allowed not to have a header file sitting around, and just magically inject the necessary code as if the header file existed, because this is a Standard Library header (thus special). For regular headers (yours) the pre-processor is invoked.
Then, at link-time:
if you use static linking, the linker will search for the Standard Library and include it in the executable it produces
if you use dynamic linking, the linker will note that it depends on the Standard Library file (libc++.so for example) and that the produced code is missing an implementation of printf (for example)
Then, at load time:
if you used dynamic linking, the loader will search for the Standard Library and load its code
Then, at execution time, the code (yours and its dependencies) is finally executed.
Several Standard Library implementations exist, off the top of my head:
MSVC ships with a modified version of Dirkumware
gcc ships with libstdc++ (which depends on libc)
clang ships with libc++ (which depends on libc), but may use libstdc++ instead (with compiler flags)
And of course, you could provide others... probably... though setting it up might not be easy.
Which is ultimately used depends on the compiler options you use. By default the most common compiler ship with their own implementation and use it without any intervention on your part.
And finally yes, you can indeed specify paths in a #include directive. For example, using boost:
#include <boost/optional.hpp>
#include <boost/algorithm/string/trim.hpp>
you can even use relative paths:
#include <../myotherproject/x.hpp>
though this is considered poor form by some (since it breaks as soon as your reorganize your files).
What matters is that the pre-processor will look through a list of directories, and for each directory append / and the path you specified. If this creates the path of an existing file, it picks it, otherwise it continues to the next directory... until it runs out (and complain).
The <iostream> file is just not needed during execution. But that's just the header. You do need the standard library, but that's generally named differently if not included outright into your executable.
The C++ Standard Library doesn't ship with your OS, although on many Linux systems the line between OS and common libraries such as the C++ Standard Library is a bit thin.
How you locate that library is very much OS dependent.
There can be 2 ways to load a header file (like iostream.h) in C++
if you write the code as:
# include <iostream>
It will look up the header file in include directory of your C++ compiler and will load it
Other way you can give the full path of the header file as:
# include "path_of_file.h"
And loading up the file is OS dependent as answered by MSalters
You definitely required the standard library header files so that pre-processor directive can locate them.
Yes those files are present in the library and on include copied to our code.
if we had defined the our own header file then we have to give path of that file. In that way we can include also *.c or *.cpp along with the header files in which we had defined various methods and those had to include at pre-processing time.
I have access to a large C++ project, full of files and with a very complicated makefile courtesy of automake & friends
Here is an idea of the directory structure.
otherproject/
folder1/
some_headers.h
some_files.cpp
...
folderN/
more_headers.h
more_files.cpp
build/
lots_of things here
objs/
lots_of_stuff.o
an_executable_I_dont_need.exe
my_stuff/
my_program.cpp
I want to use a class from the big project, declared in say, "some_header.h"
/* my_program.cpp */
#include "some_header.h"
int main()
{
ThatClass x;
x.frobnicate();
}
I managed to compile my file by painstakingly passing lots of "-I" options to gcc so that it could find all the header files
g++ my_program.cpp -c -o myprog.o -I../other/folder1 ... -I../other/folderN
When it comes to compiling I have to manually include all his ".o"s, which is probably overkill
g++ -o my_executable myprog.o ../other/build/objs/*.o
However, not only do I have to do things like manually removing his "main.o" from the list, but this isn't even enough since I forgot to also link against all the libraries that he happened to use.
otherproject/build/objs/StreamBuffer.h:50: undefined reference to `gzread'
At this point I am starting to feel I am probably doing something very wrong. How should I proceed? What is the usual and what is the best approach this kind of issue?
I need this to work on Linux in case something platform-specific needs to be done.
Generally the project's .o files should come grouped together into a library (on Linux, .a file if it's a static library, or .so if it's a dynamic library), and you link to the library using the -L option to specify the location and the -l option to specify the library name.
For example, if the library file is at /path/to/big_project/libbig_project.a, you would add the options -L /path/to/big_project -l big_project to your gcc command line.
If the project doesn't have a library file that you can link to (e.g. it's not a library but an executable program and you just want some of the code used by the executable program), you might want to try asking the project's author to create such a library file (if he/she is familiar with "automake and friends" it shouldn't be too much trouble for him), or try doing so yourself.
EDIT Another suggestion: you said the project comes with a makefile. Try makeing it with the makefile, and see what its compiler command line looks like. Does it have many includes and individual object files as well?
Treating an application which was not developed as a library as if it was a library isn't likely to work. As an offhand example, omitting the main might wind up cutting out initialization code that the class you want depends upon.
The responsible thing to do here is to read the code, understand it, and turn the functionality you want into a proper library. Build the "exe you don't need" with debug symbols and set breakpoints in the constructors and methods of the class. Step into them so you get a grasp on the functionality and what parts of the program are relevant and irrelevant to your needs.
Hopefully the code is under some kind of version control system that supports branching (such as Git). If not, make your own repository that does. Edit the files until you've organized them into a library and code that uses the library. Make sure it works properly within the context of the original program. Then turn around and use this library in your own program.
If you've done a good job, you might be able to convince the original authors to accept the separation back into their original codebase. If not, at least version control has your back so you can manage integration of future changes.
I have this library called BASS which is an audio library which I'm going to use to record with the microphone. I have all the files needed to use it, but I don't know how to install the library. I tried taking the example files and putting them in the same directory as the bass.h file. But I got a bunch of errors saying there are function calls that doesn't exist.
So my question is, how do I install it to be able to use it?
Installing a C++ library means specifying to interested software (eg. a compiler) the location of two kinds of files: headers (typical extensions *.h or .hpp) and compiled objects (.dll or *.lib for instance).
The headers will contain the declarations exposed to the developer by the library authors, and your program will #include them in its source code, the dll will contain the compiled code which will be or linked together and used by your program, and they will be found by the linker (or loaded dynamically, but this is another step).
So you need to
Put the header files in a location which your compiler is aware of (typically IDE allows to set so-called include directories, otherwise you specify a flag like -I<path-to-headers> when invoking the compiler)
Put the dll files in a location which your linker is aware of (surely your IDE will allow that, otherwise you speficy a flag like -L<path-to-libraries> -l<name-of-libraries>
Last but not least, since I see that BASS library is a commercial product, probably they will have made available some installation instructions?
Run this command in a terminal or console.
cpp -v
Notice at the end of the output, you'll see a line like this:
#include<...> search starts here:
There will be a list of directories below that line.
Move the package folder to one of those directories.
Then try importing the module with <>.
See the code below code and don not forget to put bass.dll in the directory of your exe file and include the file bass.lib with your project and don not forget also to include the path to bass.h and bass.lib in the default include and lib path of your project.
#include <iostream>
#include "bass.h"
using namespace std;
int main(int argc, const char **argv)
{
if (!BASS_Init(-1, 44100, 0, NULL ,NULL))
{
cout<<"Can't initialize device";
return -1;
}
int stream = BASS_StreamCreateFile(false, "D:\\mypro\\Trans_Langs\\germ\\quran_amma\\Translations\\Sound_aya\\Sora1\\Hafs\\basfar\\a7.mp3", 0L, 0L, 0);
if (stream != 0)
{
// play the stream channel
BASS_ChannelPlay(stream, false);
}
else
{
// error creating the stream
cout<<"Stream error: {0}", BASS_ErrorGetCode();
}
getchar();
BASS_StreamFree(stream);
// free BASS
BASS_Free();
return 0;
}
If there are files named configure, Makefile or install you can try running them in that order. After that, any program that wants to link with this library must use a command like this:
c++ <your_program.cpp> -l<library_name> -L<path_where_library_is_installed>
The library path is usually the original library folder itself, unless you explicitly change it or the library itself puts its files in global locations like /usr/local or something like that.