Cmake test : was a library compiled/linked against libc++ or libstd++? - c++

I am using cmake to manage my project that uses a third party library.
This library could have been compiled/linked against libc++ or libstd++ (Depending on the version).
I know how to tell cmake to compile/link my project against libc++ or libstdc++, but I don't know how to check if the library I am using was compiled/linked against libc++ or libstd++. Is there any cmake command to check that?

For shared libraries you can use the GetPrerequisites standard module to test if the library depends on libstc++ or libc++.
For example, the following code test if boost's program_options library has been compiled against libstc++ or libc++:
set (_library "/usr/local/lib/libboost_program_options.dylib")
set (_prequesites "")
set (_exclude_system FALSE)
set (_recurse FALSE)
set (_exePath "")
set (_searchDirs "")
get_prerequisites(${_library} _prequesites ${_exclude_system} ${_recurse} "${_exePath}" "${_searchDirs}")
if (_prequesites MATCHES "/libstdc\\+\\+")
message("using libstc++")
elseif (_prequesites MATCHES "/libc\\+\\+")
message("using libc++")
else()
message("using neither libstc++ nor libc++")
endif()
For static libraries you probably have to resort to running nm on the library file to determine external symbols and then search for characteristic strings like __gnu_ in the output.

Do you have an error if you link to the wrong version ? If it's the case, you can use try_compile from CMake. Example of use :
try_compile(
TRY_COMPILE_SUCCESS
${CMAKE_BINARY_DIR}/tmpTryDir
${CMAKE_MODULES_DIR}/SourceFile.cpp
CMAKE_FLAGS
"-DINCLUDE_DIRECTORIES=${TRY_INCLUDE_DIRS}"
"-DLINK_DIRECTORIES=${TRY_LIBRARY_DIRS}"
"-DLINK_LIBRARIES=${TRY_LIBRARIES}"
COMPILE_DEFINITIONS
"-DCOMPILER_OPTION"
)
And then, the CMake variable TRY_COMPILE_SUCCESS contains TRUE or FALSE depending of the compilation success.

Related

Problem adding std::filesystem to CMake Project

I am new to CMake projects and I want to use the file system library in my project. I am running Ubuntu 18.04 with GCC 8.2 and CMake 3.13. In order to achieve this I tried two options:
Option 1
cmake_minimum_required(VERSION 3.13)
project(TheFsProject)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_FLAGS "-std=c++17 -lstdc++fs")
This does not help as the compiler still cannot find the file system
library during compile time.
Option 2 (copied from:
https://www.scivision.co/cmake-cpp-17-filesystem/)
make_minimum_required(VERSION 3.13)
project(TheFsProject)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_REQUIRED_FLAGS -std=c++17)
include(CheckCXXSymbolExists)
CHECK_CXX_SYMBOL_EXISTS(std::filesystem::path::preferred_separator cxx17fs)
if(cxx17fs)
add_executable(TheFsProject main.cpp)
set_property(TARGET TheFsProject PROPERTY CXX_STANDARD 17)
endif()
This does not help either as I get a CMake error which I don't
understand.
(CHECK_CXX_SYMBOL_EXISTS):
CHECK_CXX_SYMBOL_EXISTS Macro invoked with incorrect arguments for macro named: CHECK_CXX_SYMBOL_EXISTS
I feel out of my depth on this topic which is why I came here. I don't mind putting extra work into finding out more but I don't know anymore where to look. Any help would be appreciated!
EDIT 1
Thanks for the replies so far! I made Option 3 based on your feedback:
cmake_minimum_required(VERSION 3.13)
project(TheFsProject)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(TheFsProject main.cpp)
target_link_libraries(TheFsProject stdc++fs)
Sadly it doesn't fix my problem. It still issues an error during compilation that it can't find the compilation header.
EDIT 2
Thanks for all the replies so far. All of these help. I tried Ashkan his answer last (because it seemed intimidating). This one returns
Compiler is missing file system capabilities.
so I'm guessing something is wrong on that end. This is useful in the sense that I now know it's probably not due to my CMake file. I now have to find out why the compiler does support the file system header though...
EDIT 3
Strictly speaking this question is answered because my question is about the CMake file. I am going to mark Ashkan his answer as the solution simply because it produced the next step in my troubleshooting search. If I could I would also mark lubgr his answer because I think that's a really good answer as well. Thanks everyone!
Gcc 8.2. comes with <filesystem>, so there is no need to investigate with regard to the availability. Next, option 1 is sufficient, but needs a fix:
set(CMAKE_CXX_STANDARD 17) # no need to manually adjust the CXXFLAGS
add_executable(yourExecutable yourSourceFile.cpp)
target_link_libraries(yourExecutable stdc++fs)
This should result in compiling the sources with -std=c++17 or -std=gnu++17 and adding -lstdc++fs when linking.
Edit: Note that as #Ashkan has pointed out in the comments, setting CMAKE_CXX_STANDARD_REQUIRED to true results in an immediate error at configure time if C++17 isn't supported by the compiler, instead of a compilation error (due to the missing <filesystem> header) or at link time (due to the missing shared library). This might be desirable.
Besides from #lubgr's answer. I think a more complete way is to also do try_compile to see that you can actually use the filesystem header. This in my opinion is better because some compilers are not supporting std::filesystem yet. Also in gcc 7.x you have the filesystem under experimental namespace. This way you can have a separate try_compile in the else clause and detect that.
Here is the related cmake for it
# set everything up for c++ 17 features
set(CMAKE_CXX_STANDARD 17)
# Don't add this line if you will try_compile with boost.
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# test that filesystem header actually is there and works
try_compile(HAS_FS "${CMAKE_BINARY_DIR}/temp"
"${CMAKE_SOURCE_DIR}/tests/has_filesystem.cc"
CMAKE_FLAGS -DCMAKE_CXX_STANDARD=17 -DCMAKE_CXX_STANDARD_REQUIRED=ON
LINK_LIBRARIES stdc++fs)
if(HAS_FS)
message(STATUS "Compiler has filesystem support")
else()
# .... You could also try searching for boost::filesystem here.
message(FATAL_ERROR "Compiler is missing filesystem capabilities")
endif(HAS_FS)
The file tests/has_filesystem.cc is very simple
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
fs::path aPath {"../"};
return 0;
}
You could in your else clause try_compile for boost::filesystem and pass a directive that can be used in your source file where you decide if you want to use c++17 filesystem or boost.
CHECK_CXX_SYMBOL_EXISTS takes three arguments, not two:
include(CheckCXXSymbolExists)
check_cxx_symbol_exists(std::filesystem::path::preferred_separator filesystem cxx17fs)
You forgot to tell CMake where to look for the symbols (the header that declares them).
I have found a case when try_compile was not enough: when using the Intel C++ compiler (icpc (ICC) 19.1.1.216 20200306) in C++17 mode running on MacOS "Mojave" 10.14.6. The test program recommended by #Ashkan compiled without errors, and it even ran. However, my code uses fs::path::filename() at one point and that resulted in a runtime linker error (dyld: lazy symbol binding failed: Symbol not found:). In other words: the header is there, the implementation apparently isn't (?). I didn't investigate this any further.
The solution is to use try_run instead of try_compile and (in my case) fall back to boost::filesystem if std::filesystem is not yet supported.
Here is the relevant CMake code section:
try_run(RUNS_WITH_STDFS COMPILES_WITH_STDFS
"${CMAKE_BINARY_DIR}/try"
"${CMAKE_SOURCE_DIR}/cmake/has_stdfs.cc"
CMAKE_FLAGS CMAKE_CXX_STANDARD=17 CMAKE_CXX_STANDARD_REQUIRED=ON
)
if (RUNS_WITH_STDFS STREQUAL "FAILED_TO_RUN")
message(STATUS "Using boost::filesystem instead of std::filesystem")
set(_boost_components ${_boost_components} filesystem system)
add_definitions(-DUSE_BOOST_FILESYSTEM)
else()
message(STATUS "std::filesystem supported")
endif()
Note that the variable RUNS_WITH_STDFS is not set to NO in case of failure but to "FAILED_TO_RUN" which is not interpreted as a FALSE Boolean (see CMake if() docs:
if() True if the constant is 1, ON, YES, TRUE, Y, or a
non-zero number. False if the constant is 0, OFF, NO, FALSE, N,
IGNORE, NOTFOUND, the empty string, or ends in the suffix -NOTFOUND.
so I had to string-compare its value.
The little test program also changed a bit compared to #Ashkan's solution:
// == PROGRAM has_stdfs.cc ==
// Check if std::filesystem is available
// Source: https://stackoverflow.com/a/54290906
// with modifications
#include <filesystem>
namespace fs = std::filesystem;
int main(int argc, char* argv[]) {
fs::path somepath{ "dir1/dir2/filename.txt" };
auto fname = somepath.filename();
return 0;
}

Cannot use the C++ `std::filesystem` library with Meson build

I am trying to build a piece of C++ code that uses the new C++17 Filesystem library, using the Meson build system.
This is the piece of meson.build file involved:
if not compiler.has_header('filesystem') # This is OK
warning('The compiler has no <filesystem> header file')
endif
filesystem_dep = dependency('libc++fs', modules : ['filesystem'])
test_exe = executable('test', test_src,
include_directories : include_dirs,
dependencies : filesystem_dep
)
In case the boost::filesystem library is used, this should be the correct syntax:
filesystem_dep = dependency('boost', modules : ['filesystem'])
How can I specify I want the version contained in the Standard C++ library? This is what I tried without success: 'libc++fs', 'stdlib', 'stdc++', 'libc++', 'c++', 'c++17'.
This is the error message I get from Meson:
src/meson.build:33:0: ERROR: Native dependency 'libc++fs' not found
The compiler I am currently using is LLVM/clang.
dependency() is for external libraries. Standard libraries should be configured using compiler command line with special functions like add_XXX_arguments(). So, try
add_project_arguments(['-stdlib=libc++'], language : 'cpp')
add_project_link_arguments(['-stdlib=libc++','-lstdc++fs'], language : 'cpp')
However, '-lstdc++fs' maybe not needed in your case.

Too many libboost_*.lib

I have downloaded boost 1.58.0 (precompiled, x86, VC 12.0) from http://boost.teeks99.com/ and installed to C:\local\boost_1_58_0 (I also tried compiled the source code using msvc-12.0 by myself and get the same result.
The problem: I see too many libboost*.lib of the same library, for example
ls -l libboost_math_* returns:
libboost_math_c99f-vc120-mt-1_58.lib
libboost_math_c99f-vc120-mt-gd-1_58.lib
libboost_math_c99f-vc120-mt-s-1_58.lib
libboost_math_c99f-vc120-mt-sgd-1_58.lib
libboost_math_c99f-vc120-s-1_58.lib
libboost_math_c99f-vc120-sgd-1_58.lib
libboost_math_c99l-vc120-mt-1_58.lib
libboost_math_c99l-vc120-mt-gd-1_58.lib
libboost_math_c99l-vc120-mt-s-1_58.lib
libboost_math_c99l-vc120-mt-sgd-1_58.lib
libboost_math_c99l-vc120-s-1_58.lib
libboost_math_c99l-vc120-sgd-1_58.lib
libboost_math_c99-vc120-mt-1_58.lib
libboost_math_c99-vc120-mt-gd-1_58.lib
libboost_math_c99-vc120-mt-s-1_58.lib
libboost_math_c99-vc120-mt-sgd-1_58.lib
libboost_math_c99-vc120-s-1_58.lib
libboost_math_c99-vc120-sgd-1_58.lib
libboost_math_tr1f-vc120-mt-1_58.lib
libboost_math_tr1f-vc120-mt-gd-1_58.lib
libboost_math_tr1f-vc120-mt-s-1_58.lib
libboost_math_tr1f-vc120-mt-sgd-1_58.lib
libboost_math_tr1f-vc120-s-1_58.lib
libboost_math_tr1f-vc120-sgd-1_58.lib
libboost_math_tr1l-vc120-mt-1_58.lib
libboost_math_tr1l-vc120-mt-gd-1_58.lib
libboost_math_tr1l-vc120-mt-s-1_58.lib
libboost_math_tr1l-vc120-mt-sgd-1_58.lib
libboost_math_tr1l-vc120-s-1_58.lib
libboost_math_tr1l-vc120-sgd-1_58.lib
libboost_math_tr1-vc120-mt-1_58.lib
libboost_math_tr1-vc120-mt-gd-1_58.lib
libboost_math_tr1-vc120-mt-s-1_58.lib
libboost_math_tr1-vc120-mt-sgd-1_58.lib
libboost_math_tr1-vc120-s-1_58.lib
libboost_math_tr1-vc120-sgd-1_58.lib
My questions:
Why are there so many lib files for one library? (36 files for
libboost_math, 4 libboost_atomic, 6 libboost_iostreams and so on)
Why are there no single libboost_math.lib, libboost_atomic, ...
files?
If I want to use boost_math, which library should I choose?
Boost.Math contains many parts, and they don't share the same library file.
The libraries' filename described what it builds for.
For example,
vc120: it builds for microsoft visual C++ 12.0 (a.k.a. 2013)
mt: will link with multithread version of C runtime. (libcmt.lib)
mt-s: will link with multithread version of shared C runtime. (msvcrt.lib)
mt-gd: will link with multithread debug version of C runtime. (libcmtd.lib)
mt-sgd: will link with multithread debug version of shared C runtime. (msvcrtd.lib)
s: will link with singlethread version of shared C runtime. (seems now VC doesn't contains one? I'm not sure.)
sgd: will link with singlethread debug version of shared C runtime. (seems now VC doesn't contains one? I'm not sure.)
If you are using Boost with Microsoft Visual C++, you will benefit from the auto-link feature. Set the additional library directory and the linker (to be exact, the boost header directs the linker) will link the correct version for you.

gnat gprbuild : how to build a dynamic dll and link with a static c++ library

I have a full Ada project I want to build to get a dynamic dll.
Therefore I have to link it with another static library (myanotherlibrary.lib).
I use this command line :
gprbuild -d "D:\My_grp_project\My_grp_project.gpr"
Here the content of the .gpr :
project My_grp_project is
Architecture := "x86";
for Languages use ("Ada");
for Source_Dirs use (".", "source", "source\common");
for Library_Dir use "dll\" & Architecture;
for Library_Ali_Dir use "ali\" & Architecture;
for Library_Name use "My_grp_project";
for Library_Kind use "dynamic";
for Object_Dir use "obj\" & Architecture;
package Linker is
for Default_Switches ("Ada") use ("-L.", "-lbar");
end Linker;
end My_grp_project;
I put "myanotherlibrary.lib" in the directory "D:\My_grp_project\", but it still doesn't link: "undefined reference to ..."
Could anyone help me please ?
Regards
Glen
Looking at the docs, I think you should be using the Library_Options attribute instead of package Linker:
for Library_Options use ("-L.", "-lbar”);
(I’m confused - do you mean myanotherlibrary.lib or bar.lib?)
I’d be a bit concerned about using a static library from a dynamic library: I’d expect the dynamic library to be built with -fPIC or equivalent switch to get position-independent code, so that the same loaded library binary can be seen at different addresses in each of the executables using it.
Here the solution I finally found.
It is not possible to link static library compiled with MSVC. I had to compile my static library with GCC (same version as the one included in GNAT).
I had to add "Library_Options" options, without "-L" and "-l" arguments (another problem I passed). Note that package Linker is not taken into account while building a dynamic library. Note also that paths shall have no spaces !
project My_grp_project is
for Languages use ("Ada");
for Source_Dirs use (".", "source", "source\common");
for Library_Dir use “dll";
for Library_Ali_Dir use "ali";
for Object_Dir use "obj";
for Library_Name use "My_grp_project";
for Library_Kind use "dynamic";
for Library_Options use ("path\myanotherlibrary.a", "path_to_GNAT\libstdc++.a");
end My_grp_project;
I builded the project in the GPS (default option) : "Build All"
In result I do have my dynamic library "libMy_grp_project.dll"
Voilà.
Thanks !

LNK2019 when including asio headers, solution generated with cmake

I am trying to port a big project from gcc (Linux) to msvc (windows), using cmake and boost libraries.
The project compile and runs fine for gcc but on msvc it returns the following error:
Dyna.obj : error LNK2019: unresolved external symbol "void __cdecl boost::throw_exception(class std::exception const &)" (?throw_exception#boost##YAXABVexception#std###Z) referenced in function "void __cdecl boost::asio::detail::do_throw_error(class boost::system::error_code const &,char const *)" (?do_throw_error#detail#asio#boost##YAXABVerror_code#system#3#PBD#Z)
I tried running a simple project using boost asio and it worked, which teorethically excludes boost build problems.
The CMakeLists.txt is as follows: (separated the parts of interest)
.
.
.
IF(WIN32)
# Flags para garantir a compilação em windows
SET(CMAKE_CXX_COMPILER icpl)
SET(TPN_WIN32 "/D WIN32")
SET(TPN_WIN32_LIB ws2_32.lib odbc32.lib odbccp32.lib)
SET(CMAKE_EXE_LINKER_FLAGS /NODEFAULTLIB:LIBC;LIBCMT)
ENDIF(WIN32)
# Comando para se livrar de warning sobre o caminho da library pthread
IF(COMMAND cmake_policy)
cmake_policy(SET CMP0003 NEW)
ENDIF(COMMAND cmake_policy)
# Configuracao do TPN REALTIME
# === inicio ===
IF (REALTIME_YES)
MESSAGE ("[TPN] REALTIME ENABLED")
set(Boost_ADDITIONAL_VERSIONS "1.45.0")
set(Boost_USE_MULTITHREAD ON)
set(Boost_USE_STATIC_LIBS ON)
FIND_PACKAGE( Boost "1.45.0" COMPONENTS system filesystem serialization program_options regex thread date_time REQUIRED)
FIND_PACKAGE( Threads REQUIRED )
set(HYDRO_CXX_FLAGS "-DREALTIME -DJOYSTICK")
set(HYDRO_CXX_LFLAGS ${Boost_LIBRARIES})
INCLUDE_DIRECTORIES(hydro)
INCLUDE_DIRECTORIES(${Boost_INCLUDE_DIR})
ENDIF (REALTIME_YES)
# === final ===
.
.
.
TARGET_LINK_LIBRARIES(Dyna
tpn
preadyn
${WHERE_PREA3D}
${WHERE_WAMIT_IO}
${WHERE_WAMIT_CONVERTER}
${WHERE_TECLINE}
${HYDRO_CXX_LFLAGS}
${TPN_WIN32_LIB}
)
Thanks in advance
Try to add the flag "/EHsc" into your TPN_WIN32 variable in cmake.
It seems that MSVC is not throwing exceptions and you need to enable it in your vcproj.
In my case, the /EHsc flag did not work. Turned out that BOOST_NO_EXCEPTIONS was defined so the compiler was searching for the "user defined" (as in boost/throw_exception.hpp) function.
Therefore, a quick fix is to write your favorite boost::throw_exception() function:
namespace boost
{
#ifdef BOOST_NO_EXCEPTIONS
void throw_exception( std::exception const & e ){
throw 11; // or whatever
};
#endif
}// namespace boost
Looks like, to be linking compatible, binary must have same structure exception handling enablement option. MSVC standard library implementation use structured exception handling option on. Looks like this is why boost::system also uses this on. You might see corresponding warnings telling you to add structure exception handling.
IF(MSVC)
ADD_DEFINITIONS("/EHsc")
ENDIF(MSVC)
When running on windows you need (by default) to link to boost.system and boost.regex
As it says here:
Note With MSVC or Borland C++ you may want to add
-DBOOST_DATE_TIME_NO_LIB and -DBOOST_REGEX_NO_LIB to your project
settings to disable autolinking of the Boost.Date_Time and Boost.Regex
libraries respectively. Alternatively, you may choose to build these
libraries and link to them.
If you don't want to link to other boost libraries then you can use the identical (non-boost) asio library from here.
In terms of your CMakeLists.txt file, you want a line such as
target_link_libraries (your_application ${Boost_LIBRARIES})
to actually link the library.
EDIT: also, have a look at How to link against boost.system with cmake, it could be that you have to specify the individual boost libraries specifically rather than ${Boost_LIBRARIES}