C++ error: undefined reference to 'clock_gettime' and 'clock_settime' - c++

I am pretty new to Ubuntu, but I can't seem to get this to work. It works fine on my school computers and I don't know what I am not doing. I have checked usr/include and time.h is there just fine. Here is the code:
#include <iostream>
#include <time.h>
using namespace std;
int main()
{
timespec time1, time2;
int temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
//do stuff here
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
return 0;
}
I am using CodeBlocks as my IDE to build and run as well. Any help would be great, thank you.

Add -lrt to the end of g++ command line. This links in the librt.so "Real Time" shared library.

example:
c++ -Wall filefork.cpp -lrt -O2
For gcc version 4.6.1, -lrt must be after filefork.cpp otherwise you get a link error.
Some older gcc version doesn't care about the position.

Since glibc version 2.17, the library linking -lrt is no longer required.
The clock_* are now part of the main C library. You can see the change history of glibc 2.17 where this change was done explains the reason for this change:
+* The `clock_*' suite of functions (declared in <time.h>) is now available
+ directly in the main C library. Previously it was necessary to link with
+ -lrt to use these functions. This change has the effect that a
+ single-threaded program that uses a function such as `clock_gettime' (and
+ is not linked with -lrt) will no longer implicitly load the pthreads
+ library at runtime and so will not suffer the overheads associated with
+ multi-thread support in other code such as the C++ runtime library.
If you decide to upgrade glibc, then you can check the compatibility tracker of glibc if you are concerned whether there would be any issues using the newer glibc.
To check the glibc version installed on the system, run the command:
ldd --version
(Of course, if you are using old glibc (<2.17) then you will still need -lrt.)

I encountered the same error. My linker command did have the rt library included -lrt which is correct and it was working for a while. After re-installing Kubuntu it stopped working.
A separate forum thread suggested the -lrt needed to come after the project object files.
Moving the -lrt to the end of the command fixed this problem for me although I don't know the details of why.

Related

My Boost #includes cause compile failure (reformulated)

When I try to #include boost 1.60 headers, gcc fails. I'm at a loss because of this and would be appreciative of any help/guidance. I am using Fedora Linux and Netbeans 8.2.
This question was originally posted under user:user11551798, for which I don't have a password since it was posted from my mobile app.
Code snippet:
#include <boost/regex.hpp>
#include <boost/xpressive/xpressive.hpp>
#include <boost/asio.hpp>
(all three fail within the #includes)
Compiler call (from Netbeans)
gcc -O ALAN ALAn.gcc
Errors (sample from asio.hpp)
g++ -g -m64 -lboost_system -c -o ALAn.o ALAn.cpp ALAn.cpp: In
Function »int main(int, char**)«: ALAn.cpp:57:23: Error: no matching function for call to
»boost::asio::ip::basic_resolver<boost::asio::ip::tcp>::basic_resolver()«
ip::tcp::resolver resolv;
^~~~~~
Compiler error displayed means "No available function"/"Unmatched external symbol".
As always, thank you for any assistance, Im currently at a loss. And of course, sorry in adv for any transgressions. Im new here.
#yksisarvinen, #Mathieu
I now installed the Boost V1.71 lib. Same problem :-(
The enlightenment came after I upgraded Boost from V1.60 to V1.71 and my problems persisted. I was sure that I had deleted the old files with rm -vf.
So I looked at this closer.
It sure was not sync(1) because some problems persisted after syncing.
I looked at the GCC tools, which I use (this is Linux). It turned out that it HAS a little known (to me) compiler cache utility, CCACHE(1).
So I cleared the compiler cache, ccache -c. This made visible that the Boost lib tool does not compile some headers for some sui-generis reason, including regex and xpressive, which I use.
So I corrected that and Voilá! everything worked :-)

How to use a dynamic lib in eclipse?

Here is an small example I did with clang++ :
===filename===
calc_mean.cpp
===filename===
===filecontent===
double mean(double a, double b) {
return (a+b) / 2;
}
===filecontent===
===filename===
calc_mean.h
===filename===
===filecontent===
double mean(double, double);
===filecontent===
===filename===
commands.sh
===filename===
===filecontent===
#/usr/bin/env bash
clang++ -c calc_mean.cpp -o calc_mean.o
ar rcs libmean.a calc_mean.o
clang++ -c -fPIC calc_mean.cpp -o calc_mean.o
gcc -shared -W1,-soname,libmean.so.1 -o libmean.so.1.0.1 calc_mean.o
clang++ main.cpp -L. -lmean -o dynamicmain -v
===filecontent===
===filename===
main.cpp
===filename===
===filecontent===
#include <stdio.h>
#include "calc_mean.h"
int main(int argc, char const* argv[])
{
double v1, v2, m;
v1 = 5.0;
v2 = 6.0;
m = mean(v1, v2);
printf("Mean: %f\n", m);
return 0;
}
===filecontent===
It worked perfectly. Now turn to eclipse, I created a project with the dynamic lib generated above in the libs folder:
(source: p.im9.eu)
Adjusted -L and -l settings accordingly:
(source: p.im9.eu)
Got these errors:
(source: p.im9.eu)
Other things I have tried:
(source: p.im9.eu)
(source: p.im9.eu)
The errors stayed the same. I almost want to bang my head against a wall now. Should I start learning cmake already?
update
I added the header file also this time, but eclipse still can't resolve the function mean (through code analysis).
It compiles without an error though, but when I run the output binary, it says:
dyld: Library not loaded: libmean.so
Referenced from: /Users/kaiyin/personal_config_bin_files/workspace/testuselib/Debug/testuselib
Reason: image not found
Edit2:
It hit me that you're on Mac, and I remembered that there's something funny about library loading. So, there are a couple reasons why you'd get Image Not Found. The below still applies, but there's another reason it could be failing. See dyld: Library not loaded: libqscintilla2.5.dylib
I don't know if eclipse on Mac even ships with GCC, or if it's clang only on that platform, but try setting DYLD_LIBRARY_PATH as a quick test to see if it's just Mac Being Special. https://superuser.com/questions/282450/where-do-i-set-dyld-library-path-on-mac-os-x-and-is-it-a-good-idea
Edit:
Yay it compiles! Now we're hitting a linking error. This one is actually pretty fun, and isn't the "common" one I listed below (namely, Unresolved Symbols). This error, "Image Not Found" usually means that the Linker found the library, but could not use it because it was compiled in an incompatible manner.
Why is it in any incompatible format? Welcome to the one feature of C++ that I hate is missing, and one of the reasons pretty much every library out there provides a C interface instead of a C++ interface.
C++ Does Not Provide a stable ABI (Application Binary Interface). This means that libraries compiled with different compilers (or even just different versions of the same compiler may not work together. 99/100 they will just outright refuse to link/work, but even if they do link, you'll get very weird, hard-to-impossible to track down bugs, etc.
Here's the tl;dr: If you want your static lib to be C++ (which i recommend) and have a C++ interface, you need to make sure the exact same version of the compiler is used to compile both your application and the static library. The easiest way to do this is to have eclipse build both the static library and the application.
This is hopefully changing with the next version of C++, as Herb Sutter has put forward a proposal to create a platform defined C++ ABI.
Original:
You need to add the folder containing calc_mean.h to the "Additional Includes" for c++ generation. You can think of include statement as cutting and pasting the contents of the file at that exact line. The error is saying "hey, i went looking for a file called calc_mean.h and couldn't find it." You need to link the library and the header (so main.cpp knows the function)
If it was an error saying "unresolved symbols", with the symbols being in your library, then you would know you've messed up with adding the library or library path (-L).
Cmake is a good tool, but it is nice to know how to use an ide. The basic steps (add library name, add library path, add directory containing library headers) are the same in eclipse, netbeans, visual studio, xcode, etc)

Internal exceptions in shared library terminate end user application

I am building a shared library which uses Boost.thread internally. As a result, Boost.system is also used since Boost.thread depends on that. My shared library exports a C interface, so I want to hide all my internal exception handling and thread usage etc from the end user. It is supposed to be a black box so to speak. However, when I link with a client application, while the program runs fine - as soon as it is time to stop the processing by invoking a library function I get:
terminate called after throwing an instance of 'boost::thread_interrupted'
I catch this exception internally in the library, so I have no idea why it is not actually being caught. The end user's program is not meant to know about or handle Boost exceptions in any way. When building the shared library, I use static linking for both Boost.thread and Boost.system so the outside world is never meant to see them. I am on GCC 4.7 on Ubuntu 12. On Windows, I have no such problems (neither with MSVC or MinGw).
(EDIT)
I am editing the question to show a minimalistic example that reproduces the problem, as per the requests in the comments.
Here first is the code for testlib.cpp and testlib.h.
testlib.cpp:
#include <boost/thread/thread.hpp>
void thread_func()
{
while(1)
{
boost::this_thread::interruption_point();
}
}
void do_processing()
{
// Start a thread that will execute the function above.
boost::thread worker(thread_func);
// We assume the thread started properly for the purposes of this example.
// Now let's interrupt the thread.
worker.interrupt();
// And now let's wait for it to finish.
worker.join();
}
And now testlib.h:
#ifndef TESTLIB_H
#define TESTLIB_H
void do_processing();
#endif
I build this into a shared library with the following command:
g++ -static-libgcc -static -s -DNDEBUG -I /usr/boost_1_54_0 -L /usr/boost_1_54_0/stage/lib -Wall -shared -fPIC -o libtestlib.so testlib.cpp -lboost_thread -lboost_system -lpthread -O3
Then, I have the code for a trivial client program which looks as follows:
#include "testlib.h"
#include <cstdio>
int main()
{
do_processing();
printf("Execution completed properly.\n");
return 0;
}
I build the client as follows:
g++ -DNDEBUG -I /usr/boost_1_54_0 -L ./ -Wall -o client client.cpp -ltestlib -O3
When I run the client, I get:
terminate called after throwing an instance of 'boost::thread_interrupted'
Aborted (core dumped)
I am not explicitly catching the thread interruption exception, but according to the Boost documentation Boost.thread does that and terminates the given thread only. I tried explicitly catching the exception from within the thread_func function, but that made no difference.
(End OF EDIT)
(EDIT 2)
It is worth noting that even with -fexceptions turned on, the problem still persists. Also, I tried to throw and catch an exception that is defined in the same translation unit as the code that catches and throws it, with no improvement. In short, all exceptions appear to remain uncaught in the shared library even though I definitely have catch handlers for them. When I compile the client file and the testlib file as part of a single program, that is to say without making testlib into a shared library, everything works as expected.
(End OF EDIT 2)
Any tips?
I finally figured it out. The -static flag should never be specified when -shared is specified. My belief was that it merely told the linker to prefer static versions of libraries that it links, but instead it makes the generated dynamic library unsuitable for dynamic linking which is a bit ironic. But there it is. Removing -static solved all my problems, and I am able to link Boost statically just fine inside my dynamic library which handles exceptions perfectly.
Maybe this?
If you have a library L which throws E, then both L and the
application A MUST be linked against X, the library containing the
definition of E.
Try to link executable against boost, too.
A shared library that itself includes statically linked libraries is not such a good idea, and I don't think that this scenario is well supported in the GNU toolchain.
I think that your particular problem arises from the option -static-libgcc, but I've been unable to compile it in my machine with your options. Not that linking statically-dinamically to libpthread.so sounds as such a good idea either... What will happen if the main executable wants to create its own threads? Will it be compiled with -pthread? If it is, then you will link twice the thread functions; if it isn't, it will have the functions but not the precompiler macros nor the thread-safe library functions.
My advice is simply not to compile your library statically, that's just not the Linux way.
Actually that should not be a real problem, even if you don't want to rely on the distribution version of boost: compile your program against the shared boost libraries and deploy all these files (libboost_thread.so.1.54.0, libboost_system.so.1.54.0 and libtestlib.so) to the same directory. Then run your program with LD_LIBRARY_PATH=<path-to-so-files>. Since the client is not intended to use boost directly, it doesn't need the boost headers, nor link them in the compiler command. You still have your black box, but now it is formed by 3 *so files, instead of just 1.

C++ runtime errors in CodeBlocks when printing strings with cout <<

I recently started using CodeBlocks and began encountering odd runtime errors which I have traced back to printing strings using cout <<. For example, even the following..
#include <string>
#include <iostream>
int main()
{
std::string str;
str = "Hi!";
std::cout << str << std::endl;
return 0;
}
results in an error. It will compile fine (using Borland) but when I run it I get a pop up window saying 'test.exe has stopped working' and in the console I get the message:
Process returned -1073741819 (0xC0000005) execution time : 1.526 s
Press any key to continue.
It compiles and runs fine in MS Visual C++ and with G++ in Ubuntu.. any thoughts would be greatly appreciated!
Cheers,
Weatherwax
My one-off comment ended up helping solve the problem so here it is packaged up as an answer for future users:
This guy had a similar issue and it ended up being a linker issue which he
fixed. The fix is the last post in the thread, although reading the
whole thread could be useful for you.
Long Story short: Borland compiler is a bit dated and annoying to use. Ended up being a linker issue within borland. Better off using a different compiler like GCC/G++ or Visual Studio compiler.
This answer is here to elaborate on the root cause of the issue.
The reason for your crashing program is because the wrong runtime library is being linked. Specifically, your example is compiled as a single threaded object file(the default) but the linking step is using the multithreaded cw32mt.lib runtime -- the "mt" suffix at the end means multithreaded.
The solution is to make sure the runtime your program is compiled to use matches with the runtime you're linking against. A few ways to do this.
Important bcc32 compile switches:
-tW Windows GUI program. WinMain() is expected
-tWC Windows Console program. main() is expected. default.
-tWR Use dynamically linked runtime. Absence implies static runtime linkage.
-tWM Use multithreaded runtime. Absence implies single thread.
Compiling your example program as single threaded like this works:
bcc32 -oexample.obj -c example.cpp
ilink32 -ap example.obj c0x32, example.exe,, cw32.lib import32.lib,,
or you can compile it as multithreaded like this(note the -tWM switch matching up with cw32mt.lib):
bcc32 -tWM -oexample.obj -c example.cpp
ilink32 -ap example.obj c0x32, example.exe,, cw32mt.lib import32.lib,,
A third approach that is easier and less error prone is to not call the linker yourself. Instead, let the compiler drive the linker indirectly(similar to gcc):
bcc32 -tWM -oexample.obj -c example.cpp
bcc32 -tWM example.obj -eexample.exe
For your simple example, it can even be shortened to:
bcc32 -eexample.exe example.cpp
Lastly, you can pass the -tW switch multiple times. For example, this command compiles your example as a console program with multithread support and dynamic runtime linkage:
bcc32 -tWM -tWR -tWC -eexample.exe example.cpp
The produced example.exe executable is much smaller and its import table has an entry for CC3250MT.DLL confirming that the borland runtime is dynamically linked.
We should not assume that a non-functioning program is caused by nonconformity to the standard or a bug in the tool we're using without first investigating user error as a potential cause (even though in this case it's tempting to do so). In the OP's case, the code::block IDE didn't have the right commands setup for the toolchain being used.

Boost program will not working on Linux

I have this program which uses Boost::Asio for sockets. I pretty much altered some code from the Boost examples. The program compiles and runs just like it should on Windows in VS. However, when I compile the program on Linux and run it, I get a Segmentation fault.
I posted the code here
The command I use to compile it is this:
c++ -I/appl/htopopt/Linux_x86_64/NTL-5.4.2/include
-I/appl/htopopt/Linux_x86_64/boost_1_43_0/include
mpqs.cpp mpqs_polynomial.cpp mpqs_host.cpp -o mpqs_host
-L/appl/htopopt/Linux_x86_64/NTL-5.4.2/lib -lntl
-L/appl/htopopt/Linux_x86_64/gmp-4.2.1/lib -lgmp -lm
-L/appl/htopopt/Linux_x86_64/boost_1_43_0/lib -lboost_system
-lboost_thread -static -lpthread
By commenting out code, I have found out that I get the Segmentation fault due to the following line:
boost::asio::io_service io_service;
Can anyone provide any assistance, as to what may be the problem (and the solution)?
Thanks!
Edit: I tried changing the program to a minimal example, using no other libraries or headers, just boost/asio.hpp:
#define DEBUG 0
#include <boost/asio.hpp>
int main(int argc, char* argv[]) {
boost::asio::io_service io_service;
return 0;
}
I also removed other library inclusions and linking on compilation, however this minimal example still gives me a segmentation fault.
From the GCC online documentation of the -static option:
On systems that support dynamic linking, this prevents linking with the shared libraries.
Boost can support static-only linkage but only if it was configured that way when the OS Package maintainer built it. Are you absolutely certain you should be using this flag? If not, try recompiling without the flag and see if that doesn't take care of the problem.