Thebeginner Thebeginner - 7 days ago 5
C++ Question

C++ Undefined reference when using class member in constructor

I am pretty new to C++, so the question might sound stupid, but even though I googled quite some time, I could not find an answer. I am using the ROS environment, but my question should be a general C++ problem, so I decided to post it here.

I have two codes

1)

ros::Duration max_storage_time = ros::Duration().fromNSec(1ULL * 1000000000LL);
tf::TimeCache odometryCache(max_storage_time);


2)

tf::TimeCache odometryCache(ros::Duration max_storage_time = ros::Duration().fromNSec(1ULL * 1000000000LL));


The second one compiles, while the first one does not. To me, the seem to be exactly the same. The error for the first code is:
undefined reference to
tf::TimeCache::TimeCache(ros::Duration)


The documentation of tf::TimeCache can be found at http://docs.ros.org/jade/api/tf/html/c++/classtf_1_1TimeCache.html#acca87a70aeb9c3573cdbfec26f6bfe23

Could somebody please tell me what I am missing? Where is the difference between the code pieces and why does the first one not compile?

Thanks in advance!

Answer

The problem is that you're not linking properly with the ROS libraries.
The solution is to set up your linker properly.

Only the first one actually calls any ROS functions - the second declares a function that takes a ros::Duration and returns a tf::TimeCache (This is called "the most vexing parse").

If you never try to use odometryCache, the second will not cause any problems.
If you do (for instance, odometryCache.clearList()) the compiler will complain that you're trying to access a member of a non-aggregate type, or something along those lines.

If you don't try to name the constructor's argument:

tf::TimeCache odometryCache(ros::Duration().fromNSec(1ULL * 1000000000LL));

it will compile, but linking will fail just like for the first piece.

Comments