I tried to use -rdynamic option in my CMakeLists.txt file, like this:
cmake_minimum_required(VERSION 3.5)
project(Tmuduo CXX)
...
set(CMAKE_CXX_STANDARD 11)
set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
add_compile_options(-Wthread-safety )
endif()
add_compile_options(
# -DVALGRIND
-Wall
-Wno-unused-parameter
-Woverloaded-virtual
-Wpointer-arith
-Wwrite-strings
-O3
-rdynamic
)
...
When I use cmake .. -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang and make VERBOSE=1, I got some message as follow:
Just as you can see, the -rdynamic compile option did appear in the clang++ command and the compiler also complainted that the argument was unused. But when I used the command below, something strange happended.
clang++ -I/home/phoenix/MyProject/Tmuduo -g -Wthread-safety -Wall -Wno-unused-parameter -Woverloaded-virtual -Wpointer-arith -Wwrite-strings -rdynamic -std=gnu++11 test/Exception_test.cc base/Exception.cc base/CurrentThread.cc -o exception_test -O3
Everything goes well. This time, the -rdynamic option works. That reall make me confuse. Can anyone tell me what's going on here? Why the clang++ command works while the cmake failed?
Because -rdynamic is a linker option, so if you use when compiling a source file into an object *.o it does nothing, there is no link phase here.
When linking all the *.o and libraries into the finally executable, then it is actually used.
From man gcc (but clang uses the same):
-rdynamic
Pass the flag -export-dynamic to the ELF linker, on targets that support it.
This instructs the linker to add all symbols, not only used ones, to the
dynamic symbol table. This option is needed for some uses of "dlopen" or to
allow obtaining backtraces from within a program.
Related
I'm building a library (libproj) using g++-9 and CMake (on Xenial, on Travis), so I can statically link it in a Rust crate. My build.rs sets up and runs CMake with the following config:
cmake proj-7.0.1
-DBUILD_SHARED_LIBS=ON
-DBUILD_TESTING=OFF
-DCMAKE_BUILD_TYPE=Release
-DCMAKE_CXX_FLAGS="-std=c++11 -fPIC"
-DCMAKE_INSTALL_PREFIX=[path snipped]/out
-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64
-DCMAKE_C_COMPILER=/usr/bin/gcc-9
-DCMAKE_CXX_COMPILER=/usr/bin/g++-9
-DCMAKE_ASM_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64
-DCMAKE_ASM_COMPILER=/usr/bin/gcc-9
Which builds and installs libproj successfully.
I then tell cargo to statically link it:
cargo:root=[path snipped]/out
cargo:rustc-link-search=native=[path snipped]/out/lib
cargo:rustc-link-lib=static=proj
However, the link step fails, saying I can't use relocation in a shared object:
note: /usr/bin/ld: [path snipped]/out/lib/libproj.a(4D_api.cpp.o): relocation
R_X86_64_32 against `.rodata.str1.8' can not be used when making a
shared object; recompile with -fPIC`
[path snipped]/out/lib/libproj.a(4D_api.cpp.o): error adding symbols: Bad value
collect2: error: ld returned 1 exit status
What am I doing wrong here? I've also tried to build libproj as a static lib by setting BUILD_SHARED_LIBS to OFF as per the install instructions, but that hasn't had any effect.
UPDATE:
I've managed to enable PIC for g++ (by default it's only enabled for gcc)
running: "cmake" "-Wdev" "--debug-output" "[snipped]/proj-7.0.1" "-DCMAKE_CXX_FLAGS=-std=c++11" "-DCMAKE_CXX_FLAGS=-fPIC" "-DBUILD_SHARED_LIBS=OFF" "-DCMAKE_INSTALL_PREFIX=[snipped]/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_C_COMPILER=/usr/bin/gcc-9" "-DCMAKE_CXX_COMPILER=/usr/bin/g++-9" "-DCMAKE_ASM_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_ASM_COMPILER=/usr/bin/gcc-9" "-DCMAKE_BUILD_TYPE=Debug" "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON"
Resulting in the following g++-9 invocation, which includes -fPIC:
/usr/bin/g++-9 -DCURL_ENABLED -DMUTEX_pthread -DPROJ_LIB=\"/[snip]/proj\" -DTIFF_ENABLED -I/[snip]/src -I/[snip]/include -I/[snip]/src -I/usr/include/x86_64-linux-gnu -fPIC -g -fvisibility=hidden -Wall -Wextra -Wswitch -Wshadow -Wunused-parameter -Wmissing-declarations -Wformat -Wformat-security -std=c++11 -o CMakeFiles/proj.dir/aasincos.cpp.o -c /[snip]/proj/proj-7.0.1/src/aasincos.cpp
However, I know get a completely different error (thousands of lines), that looks like my static library hasn't been correctly linked to the c++11 stdlib:
Error:
undefined reference to std::allocator<char>::allocator()
UPDATE 2:
I've managed to remove the -nodefaultlibs flag from ld. The latest g++ invocation:
/usr/bin/g++-9 -I/[snipped]/src -I/[snipped]/include -I/[snipped]/src -isystem /[snipped]/include -isystem /[snipped]/googletest -fPIC -g -fvisibility=hidden -Wall -Wextra -Wswitch -Wshadow -Wunused-parameter -Wmissing-declarations -Wformat -Wformat-security -pthread -std=c++11 -o CMakeFiles/proj_context_test.dir/proj_context_test.cpp.o -c /[snipped]/proj_context_test.cpp
And I've managed to add lstdc++ to the linker invocation:
"cc" "-Wl,--as-needed" "-Wl,-z,noexecstack" "-m64" "-L" "/[snip]/lib" "/home/travis/build/georust/proj-sys/target/debug/deps/proj_sys-95cbd73f2c3f0bde.20tasg77xuhsj5z6.rcgu.o" "/home/travis/build/georust/proj-sys/target/debug/deps/proj_sys-95cbd73f2c3f0bde.57y4784ihm3qw715.rcgu.o" "-o" "/[snip]/deps/proj_sys-95cbd73f2c3f0bde" "/home/travis/build/georust/proj-sys/target/debug/deps/proj_sys-95cbd73f2c3f0bde.3kiafs23968zh4mj.rcgu.o" "-Wl,--gc-sections" "-pie" "-Wl,-zrelro" "-Wl,-znow" "-L" "/home/travis/build/georust/proj-sys/target/debug/deps" "-L" "/home/travis/build/georust/proj-sys/target/debug/build/proj-sys-aff2ac9d43b77886/out/lib" "-L" "/home/travis/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib" "-lsqlite3" "-lcurl" "-ltiff" "-lstdc++" "-Wl,-Bstatic" "-Wl,--whole-archive" "-lproj" "-Wl,--no-whole-archive" [trimmed rlib details] "-Wl,--end-group" "/home/travis/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/x86_64-unknown-linux-gnu/lib/libcompiler_builtins-2541f1e09df1c67d.rlib" "-Wl,-Bdynamic" "-ldl" "-lrt" "-lpthread" "-lgcc_s" "-lc" "-lm" "-lrt" "-lpthread" "-lutil" "-lutil"
But the undefined reference error remains.
As I can see from your example, you have quotation marks around CMAKE_CXX_FLAGS and do not have ones around CMAKE_C_FLAGS. It looks odd.
I have built libgproj myself with cmake + your flags and with make VERBOSE=1.
I can see, that C-files compiled without fPIC, m64 and fdata-sections. I suppose, that the cause is in the quotation marks around CMAKE_C_FLAGS. I saw your log in Travis, and there is configuration for cmake from cargo:
"cmake" "/home/travis/build/georust/proj-sys/PROJSRC/proj/proj-7.0.1" "-DBUILD_SHARED_LIBS=ON" "-DBUILD_TESTING=OFF" "-DCMAKE_BUILD_TYPE=Release" "-DCMAKE_CXX_FLAGS=-std=c++11 -fPIC" "-DCMAKE_INSTALL_PREFIX=/home/travis/build/georust/proj-sys/target/debug/build/proj-sys-03a5fe6428bb060a/out" "-DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_C_COMPILER=/usr/bin/gcc-9" "-DCMAKE_CXX_COMPILER=/usr/bin/g++-9" "-DCMAKE_ASM_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64" "-DCMAKE_ASM_COMPILER=/usr/bin/gcc-9"
Note, that -DCMAKE_C_FLAGS and CMAKE_CXX_FLAGS escaped with their values, and not values by itself. I suppose, that these options become in the shell:
cmake -DCMAKE_C_FLAGS= -ffunction-sections -fdata-sections -fPIC -m64 -DCVMAKE_CXX_FLAGS=-std=c++11 -fPIC
I have tried this command, without quotation marks and cmake just ignored unknown options. So it will not fail.
I suggest you to add cmake option -DCMAKE_VERBOSE_MAKEFILE:BOOL=ON to cmake configuration or VERBOSE=1 to the make options, if you can, and then you can see real compile options passed to gcc in Travis.
You will see somethig like this:
[ 19%] Building C object src/CMakeFiles/proj.dir/wkt1_generated_parser.c.o
cd [some path]/PROJ/cmake_build/src && /usr/bin/cc -DCURL_ENABLED -DMUTEX_pthread
-DPROJ_LIB=\"/usr/local/share/proj\" -DTIFF_ENABLED -I[some path]PROJ/src -I[some
path]/PROJ/include -I[some path]/PROJ/cmake_build/src -O3 -DNDEBUG -
fvisibility=hidden -Wall -Wextra -Wswitch -Wshadow -Wunused-parameter -Wmissing-
declarations -Wformat -Wformat-security -Wmissing-prototypes -std=c99 -o
CMakeFiles/proj.dir/wkt1_generated_parser.c.o -c [some
path]/PROJ/src/wkt1_generated_parser.c
Conclusion:
You can try adding verbosity to see real compile options.
You can try to escape options properly, if it's necessary after first step.
Also I want to note, that SHARED_BUILD_LIBS=ON in my test forbids building static lib, which you want to link. When I set shared libs building setting option to OFF, static lib was built.
I recently installed LLVM v8.0.0 (on RHEL 7.4). I am going through the LLVM Kaleidoscope tutorial to learn how to use the system, but am running into an issue linking.
Per the tutorial (end of chapter 2), I run:
clang++ -g -O3 kld.cpp `llvm-config --cxxflags` -o kld
It compiles, but the linker fails on:
/tmp/kld-f7264f.o:(.data+0x0): undefined reference to `llvm::EnableABIBreakingChecks'
clang-8: error: linker command failed with exit code 1 (use -v to see invocation)
I suspected this may have been an issue with llvm-config, so I also tried using the --ldflags and --system-libs flags, but no luck.
llvm-config --cxxflags gives (reformatted for readability)
-I~/project/llvm-src/include -I~/project/llvm-build/include
-fPIC -fvisibility-inlines-hidden
-std=c++11
-Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual
-Wno-missing-field-initializers -pedantic -Wno-long-long
-Wno-maybe-uninitialized -Wdelete-non-virtual-dtor -Wno-comment
-g
-fno-exceptions -fno-rtti
-D_GNU_SOURCE -D_DEBUG -D__STDC_CONSTANT_MACROS
-D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS
Where ~/... is just the path to my home directory (edited for privacy; the actual output is a fullpath). I am working on a shared system that requires I install new software locally.
The tutorial code never references ABI explicitly, so I assume this must be some kind of compiler-flags issue. greping for the missing symbol in non-binary files gives an extern declaration in include/llvm/Config/abi-breaking.h and the real declaration in lib/Support/Error.cpp:
#if LLVM_ENABLE_ABI_BREAKING_CHECKS
int EnableABIBreakingChecks;
#else
int DisableABIBreakingChecks;
#endif
I thought I would try re-compiling, then, with -DLLVM_ENABLE_ABI_BREAKING_CHECKS. That also does that work.
I'm not really clear what the ABI breaking checks are doing in the first place, and this may be way over my C++ comfort level. But how can I silence this error, if I don't need the referenced functionality; or fix it, if i do?
Thanks.
Turns out the answer was hidden in abi-breaking.h:
/* Allow selectively disabling link-time mismatch checking so that header-only
ADT content from LLVM can be used without linking libSupport. */
#if !LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING
I'm not sure if I'll need libSupport down the line, but compiling with LLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING=1 works for the time being.
Add linkage with LLVMSupport library will also solve this problem.
With this CMake snippet:
find_package(LLVM REQUIRED CONFIG)
message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}")
message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}")
add_executable(main main.cpp)
target_link_libraries(main LLVMSupport)
Based on the discussion in llvm irc channel.
Try the following command to compile : clang++ -O3 -c $(llvm-config --cxxflags) source_file.cpp -o obj_code.
Then try linking with this command : clang++ obj_code $(llvm-config --ldflags --libs) -lpthread.
I think linking part doesn't mentioned in the kaleidoscope section. The above solution worked for me.
I don't know the influence and reason why it works. But when I add -DLLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING, the errors disappear.
clang++ xxx -DLLVM_DISABLE_ABI_BREAKING_CHECKS_ENFORCING
ref:
https://www.coder.work/article/6278120
https://blog.csdn.net/qq_37887537/article/details/112790961
My cmake file:
cmake_minimum_required(VERSION 3.10)
set(CMAKE_CXX_COMPILER "gcc-7")
project(invertedindex)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Wconversion -O0")
set(SOURCE_FILES main.cpp inverted_index.hpp params.hpp)
add_executable(invertedindex ${SOURCE_FILES})
Fortunately I looked at the generated compiler command
/usr/local/bin/gcc-7 -Wall -Wextra -Wconversion -O0 -std=gnu++1z -o CMakeFiles/invertedindex.dir/main.cpp.o -c /Users/adam/school/cpp/invertedindex/main.cpp
and saw -std=gnu++1z. I have no interest in studying long hours what the f*ck that is and why it is there when I have
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
It suspect that -std=gnu++1z is not a stable, finished library, or sth. But gcc 7 supports most of the features of c++17 standard.
when I chickened out of knowing that it should work, I replaced manually the generated command parameter to -std=gnu++17 and it worked. What's wrong? How do I make it work in cmake?
See how to specify compiler in cmake
I was using the third method which is marked with avoid.
First method, that is setting CXX env var didn't work (compiler was some Mac g++).
So I tried the second method - specifying compiler in cmake args -D CMAKE_C_COMPILER=gcc-7, which worked. Even though generating again c++1z param. I don't understand it, but until I breaks I'm good.
/usr/local/bin/gcc-7 -Wall -Wextra -Wconversion -O0 -g -std=gnu++1z -o CMakeFiles/invertedindex.dir/main.cpp.o -c /Users/adam/school/cpp/invertedindex/main.cpp
I have a C project which compiles successfully. Now I want to use C++ code in the same project, so I renamed main.c to main.cpp. The project is for an embedded microcontroller, so I'm cross compiling with the arm-none-eabi toolchain.
When I have renamed the main file to .cpp, I get the following error:
Linking CXX executable discovery_simple_test.elf
/usr/lib/gcc/arm-none-eabi/<long_path>/fpu/libg.a(lib_a-abort.o): In function `abort':
/build/<long_path>/newlib/libc/stdlib/abort.c:63: undefined reference to `_exit'
This is because some standard libraries are not available for this "bare metal" target. (see https://stackoverflow.com/a/13237079/507369)
This is solved in my linker script:
/* Remove information from the standard libraries */
/DISCARD/ :
{
libc.a ( * )
libm.a ( * )
libgcc.a ( * )
}
The linker script is added by my CMake toolchain file:
INCLUDE(CMakeForceCompiler)
SET(CMAKE_SYSTEM_NAME Generic)
SET(CMAKE_SYSTEM_VERSION 1)
# specify the cross compiler
CMAKE_FORCE_C_COMPILER(arm-none-eabi-gcc GNU)
CMAKE_FORCE_CXX_COMPILER(arm-none-eabi-g++ GNU)
SET(LINKER_SCRIPT ${CMAKE_SOURCE_DIR}/STM32F407VGTx_FLASH.ld)
SET(COMMON_FLAGS "-mcpu=cortex-m4 -mthumb -mthumb-interwork -mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffunction-sections -fdata-sections -g -fno-common -fmessage-length=0")
UNSET(CMAKE_CXX_FLAGS CACHE)
UNSET(CMAKE_C_FLAGS CACHE)
UNSET(CMAKE_EXE_LINKER_FLAGS CACHE)
SET(CMAKE_CXX_FLAGS "${COMMON_FLAGS} -std=c++11" CACHE STRING "" FORCE)
SET(CMAKE_C_FLAGS "${COMMON_FLAGS} -std=gnu99" CACHE STRING "" FORCE)
SET(CMAKE_EXE_LINKER_FLAGS "-Wl,--gc-sections -Wl,-T ${LINKER_SCRIPT}" CACHE STRING "" FORCE)
My CMakeLists.txt looks like:
project(discovery_simple_test CXX C ASM)
add_definitions(-DSTM32F407xx)
file(GLOB_RECURSE USER_SOURCES "Src/*.c" "Src/*.cpp")
include_directories(Inc)
add_executable(${PROJECT_NAME}.elf ${USER_SOURCES} ${LINKER_SCRIPT})
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-Map=${PROJECT_SOURCE_DIR}/build/${PROJECT_NAME}.map")
When linking as a C executable, this works. When linking as a C++ executable I get the undefined reference error.
Update
I looked at the exact linker commands composed by CMake and those are:
For GCC (successful):
/usr/bin/arm-none-eabi-gcc -mcpu=cortex-m4 -mthumb -mthumb-interwork
-mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffunction-sections -fdata-sections
-g -fno-common -fmessage-length=0 -std=gnu99 -Wl,-gc-sections
-T /path/STM32F407VGTx_FLASH.ld -Wl,
-Map=/path/build/discovery_simple_test.map
CMakeFiles/discovery_simple_test.elf.dir/Src/main.c.obj
<list of obj files>
-o discovery_simple_test.elf libCMSIS.a
For G++ (Error):
/usr/bin/arm-none-eabi-g++ -mcpu=cortex-m4 -mthumb -mthumb-interwork
-mfloat-abi=hard -mfpu=fpv4-sp-d16 -ffunction-sections -fdata-sections
-g -fno-common -fmessage-length=0 -std=c++11 -Wl,-gc-sections
-T /home/niels/Dev/stm32/discovery_simple_test/STM32F407VGTx_FLASH.ld
-Wl
-Map=/path/discovery_simple_test/build/discovery_simple_test.map
CMakeFiles/discovery_simple_test.elf.dir/Src/stm32f4xx_hal_msp.c.obj
CMakeFiles/discovery_simple_test.elf.dir/Src/stm32f4xx_it.c.obj
CMakeFiles/discovery_simple_test.elf.dir/Src/main.cpp.obj
<List of obj files>
-o discovery_simple_test.elf libCMSIS.a
So at least the parameters passed to g++ are the ones I expected. I tried removing --gc-sections in combination with adding -nostartfiles, but this didn't help.
I'm not sure if there's a more CMakeish way to do this, but try adding -specs=nosys.specs your CMake toolchain file like so:
SET(CMAKE_EXE_LINKER_FLAGS "-specs=nosys.specs, -Wl,--gc-sections -Wl,-T ${LINKER_SCRIPT}" CACHE STRING "" FORCE)
"nosys" is generic implementation for barebone systems.
https://launchpadlibrarian.net/170926122/readme.txt
The missing functions have to provide the interface between newlib and the hardware or the OS, these are called the system calls.
The linking issue can be solved by adding the --specs=nosys.specs command line option as stated by user Cinder Biscuits. This option provides mostly non-functional implementations of the system calls.
But this only solves the linking issue, if functionality from newlib is actually required, an implementation of the system calls needs to be provided.
A guide for developing the system calls can be found here.
For the STM32 microcontrollers, ST provides a file syscalls.c as part of their STM32CubeF4 software package. The file can be found in the package at Projects/STM32F4-Discovery/Examples/BSP/SW4STM32/. By adding this file to the project, implementations for all the syscalls are provided and newlib can be used.
For a small microcontroller like the STM32, newlib nano should be used as it is much smaller. This can be achieved by adding the --specs=nano.specs command line parameter.
Linking CXX executable discovery_simple_test.elf
/usr/lib/gcc/arm-none-eabi//fpu/libg.a(lib_a-abort.o): In function abort':
/build/<long_path>/newlib/libc/stdlib/abort.c:63: undefined reference to_exit'
The _exit function is part of newlib (check newlib/_exit.c ). Try adding following flag to the CMAKE_EXE_LINKER_FLAGS: --specs=nano.specs
As you are on a freestanding system it makes also sense to add -ffreestanding to both – C and C++ – compiler flags.
I'm developing applications in C++11 and my compiler is CLang++ 3.3. I'm also using Netbeans 7.3 IDE on Linux Mint 14.
All of my tests are done with GoogleTest (gtest-1.6.0) and almost everything is working fine except the warning mentioned in the title of this post.
Here's the command line executed by netbeans as an example:
clang++ -pedantic-errors -lgtest -pthread -c -g -Wall -std=c++11 -pedantic-errors -lgtest -pthread -MMD -MP -MF build/Debug/CLang-Linux-x86/_ext/1802678175/main.o.d -o build/Debug/CLang-Linux-x86/_ext/1802678175/main.o ../GIT_CryptoCode/src/main.cpp
I don't know why, but the command contains twice some attributes which gives the same warning twice of course. This is what I did in the project properties :
If I remove the Additional options, gtest is not working and the command line becomes something like this : clang++ -c -g -Wall -std=c++11 .... What should I do to not get some attributes to be duplicates ?
Well, even with cmake, I got the warning with Clang (which appears once this time :)). I also tested with GCC 4.7 and I didn't get any warning. Here's the command line I use in a cmake file for GCC :
set (CMAKE_CXX_FLAGS "-Winline -Wall -Werror -pedantic-errors -pthread -std=c++11")
Thus, Clang seems to be the problem. Is anyone know where this warning come from and how to remove it ? Is this a Clang bug ?
Thanks for your help.
I want to thank #Fraser for his help that helps me to find out the way to remove the warnings. Basically, instead of writing -pedantic-errors -lgtest -pthread in the Additional options of the C++ compiler section which gives a duplicate warning, these attributes should be in the Linker section of the project.
So, the Additional Options in the C++ compiler section are left empty. Now, I can use the -Werror attribute without any problem.
Also, in the cmake file, the line
target_link_libraries(${Project_Name} ${GTEST_BOTH_LIBRARIES})
links the gtest library to the project. Thus, no need of -lgtest in
set (CMAKE_CXX_FLAGS "-Winline -Wall -Werror -pedantic-errors -pthread -std=c++11")
both, for GCC and Clang.