GCC debugger stack trace displays wrong file name and line number - c++

I am trying to port a fairly large C++ project to using g++ 4.0 on Mac OS X. My project compiles without errors, but I can't get GDB to work properly. When I look at the stack by typing "bt" on the GDB command line, all file names and line numbers displayed are wrong.
For example, according to the GDB stack trace, my main() function is supposed to be in stdexcept from the Mac OS X SDK, which does not make any sense.
What could cause GDB to malfunction so badly? I've already checked for #line and #file statements in my code and made sure that the code only has unix line endings. I've also cleaned and rebuilt the project. I've also tried debugging a Hello World project and that one did not have the same problem.
Could the problem have to do with one of the third party libraries I am linking and the way those are compiled? Or is it something completely different?
Here are two exemplary calls to gcc and ld as executed by Xcode. AFAIK all cpp-files in my project are compiled and linked with the same parameters.
/Developer/usr/bin/gcc-4.0 -x c++
-arch i386 -fmessage-length=0 -pipe -Wno-trigraphs -fpascal-strings -fasm-blocks -O0 -fpermissive -Wreturn-type -Wunused-variable -DNO_BASS_SOUND -D_DEBUG -DXCODE -D__WXMAC__ -isysroot /Developer/SDKs/MacOSX10.5.sdk
-mfix-and-continue -fvisibility-inlines-hidden -mmacosx-version-min=10.4 -gdwarf-2 -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -D__WXDEBUG__ -D__WXMAC__ -c "/Users/adriangrigore/Documents/Gemsweeper
Mac/TSDLGameBase.cpp" -o
"/Users/adriangrigore/Documents/Gemsweeper
Mac/build/Gemsweeper
Mac.build/Debug/Gemsweeper
Mac.build/Objects-normal/i386/TSDLGameBase.o"
/Developer/usr/bin/g++-4.0 -arch i386
-isysroot /Developer/SDKs/MacOSX10.5.sdk
"-L/Users/adriangrigore/Documents/Gemsweeper
Mac/build/Debug"
-L/Developer/SDKs/MacOSX10.5.sdk/usr/local/lib
-L/opt/local/lib "-F/Users/adriangrigore/Documents/Gemsweeper
Mac/build/Debug"
-F/Users/adriangrigore/Library/Frameworks
-F/Developer/SDKs/MacOSX10.5.sdk/Library/Frameworks
-filelist "/Users/adriangrigore/Documents/Gemsweeper
Mac/build/Gemsweeper
Mac.build/Debug/Gemsweeper
Mac.build/Objects-normal/i386/Gemsweeper
Mac.LinkFileList"
-mmacosx-version-min=10.4 /opt/local/lib/libboost_program_options-mt.a
/opt/local/lib/libboost_filesystem-mt.a
/opt/local/lib/libboost_serialization-mt.a
/opt/local/lib/libboost_system-mt.a
/opt/local/lib/libboost_thread-mt.a
"/Users/adriangrigore/Documents/Gemsweeper
Mac/3rd
party/FreeImage/Dist/libfreeimage.a"
"/Users/adriangrigore/Documents/Gemsweeper
Mac/3rd
party/cpuinfo-1.0/libcpuinfo.a"
-L/usr/local/lib -framework IOKit -framework Carbon -framework Cocoa -framework System -framework QuickTime -framework OpenGL -framework AGL -lwx_macd_richtext-2.8 -lwx_macd_aui-2.8 -lwx_macd_xrc-2.8 -lwx_macd_qa-2.8 -lwx_macd_html-2.8 -lwx_macd_adv-2.8 -lwx_macd_core-2.8 -lwx_base_carbond_xml-2.8 -lwx_base_carbond_net-2.8 -lwx_base_carbond-2.8 -framework SDL -framework Cocoa -o "/Users/adriangrigore/Documents/Gemsweeper
Mac/build/Debug/Gemsweeper
Mac.app/Contents/MacOS/Gemsweeper Mac"
Please note that I have already asked a similar question regarding the Xcode debugger here, but I am reposting since I just learned that this is in fact not Xcode's fault, but a problem with GCC / ld / GDB.
Edit: My project makes use of the following third-party libraries: SDL, Boost, wxWidgets. I am not sure if this matters for this problem, but I just wanted to mention it just in case it does.
I've tried compiling an Xcode SDL project template and did not experience the same problem, so it must be due to something special in my project.
Second Edit: As I just found out, I made a mistake while searching files with the string "This is an automatically generated". I just found several dozen files with the same string, all belonging to FreeImage, one of the third party libraries I am using. So, the problem seems to be related to FreeImage, but I am not still not sure how to proceed.

I got those symptoms, when my gdb version didn't match my g++ version.
Try to get the newest gdb.

Your cpp files certainly have debug symbols in them (the -gdwarf-2 option).
Do you use a separate dSYM file for the debug symbols? Or are they inside the object files. I would first try to use DWARF in dSYM files and see if that helps (or vice versa)
The third party libraries appear to be release builds though (unless you renamed them yourself of course) e.g. I know for sure boost uses the -d monniker in the library names to denote debug libraries (e.g. libboost_filesystem-mt-d.a).
Now, this shouldn't really pose a problem, it should just mean you can't step into the calls made to third party libraries. (at least not make any sense of it when you do ;) But since you have problems, it might be worth a try to link with debug versions of those libraries...

Are you compiling with optimization on? I've found that O2 or higher messes with the symbols quite a bit, making gdb and core files pretty much useless.
Also, be sure you are compiling with the -g option.

Can it be that you are using SDL? SDL redefines main so your main will be named SDL_main and that the SDL parts might be heavy optimized so down there you'll have problem getting good gdb output.
...just a thought
Read this

For a test, you could check if addr2line gives you expected values. If so, this would indicate that there's nothing wrong with the ELF generated by your compile/link parameters and casts all suspicion on GDB. If not, then suspicion is still on both the tools and the ELF file.

I've tried compiling an XCode SDL
project template and did not
experience the same problem, so it
must be due to something special in my
project.
Correct. Your project settings are the thing that is different.
You will need to disable the debug optimizations in the Xcode project settings for the debug build. Xcode unfortunately makes GDB jump to weird lines (out of order) when you would expect it to move sequentially.
Go to your project settings. Set the following
1) Instruction Scheduling = None
2) Optimization Level = None [-O0]
3) ZERO_LINK = None
Your problems should go after after doing this.
Here is the project settings screen that you need to change the settings on:

From your flags the debug information should be in the object files.
Does your project settings build the executable in one location then move the final executable to another location when completed? If this is the case then gdb may not be finding the objectects files and thus not correctly retrieving the debug information from the object files.
Just a guess.

I encountered this several years ago when transitioning from the Codewarrior compilers to Xcode. I believe the way to get around this is to put the flag "-fno-inline-functions" in Other C Flags (for Dev only).
This problem was more pronounced on the PowerPC architecture for us.
What about if you remove the "-fvisibility-inlines-hidden" and "-mfix-and-continue" flags?
I've never had the "fix and continue" feature work properly for me.

WxWidgets do also define their own main if you use their IMPLEMENT_APP() macro
From here
As in all programs there must be a "main" function. Under wxWidgets main is implemented using this macro, which creates an application instance and starts the program.
IMPLEMENT_APP(MyApp)

See my answer here
I have now downloaded and compiled the FreeImage sources and yes, the file b44ExpLogTable.cpp is compiled into libfreeimage.a. The problem looks like the script gensrclist.sh just collects all .cpp files without skipping the one with a main in. That script generates a file named Makefile.srcs but one is already supplied. (running it on my Leopard failed, some problem with sh - it worked if I changed sh to bash)
Before you have changed anything this gives an a.out
c++ libfreeimage.a
The file Makefile.srcs has already been created so you should be able to remove the file b44ExpLogTable.cpp from it. Then do
make -f Makefile.osx clean
make -f Makefile.osx
When this is done the above c++ libfreeimage.a should give the following error
Undefined symbols:
"_main", referenced from:
start in crt1.10.5.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

I have a new thing you can try.
Just before your own main you can write
#ifdef main
# error main is defined
#endif
int main(int argc, char *argv[]) {
this should give an error if you have some header that redefines main.
If you define an own you might get an warning where a previous definition was made
#define main foo
int main(int argc, char *argv[]) {
You can also try to undef just before your main
#undef main
int main(int argc, char *argv[]) {

Related

Problems with including custom c++ library in Visual Studio Code

I was trying to include the GMP library, which was simply the code below(I did nothing else):
#include <gmpxx.h>
However, when I tried to compile the code, the following error from g++ compiler occured:
myCode.cpp:3:10: fatal error: gmpxx.h: No such file or directory
#include <gmpxx.h>
^~~~~~~~~~~~~~~~~~~~~~
I have tried everything I searched online, putting the GMP lib here and there, adding INFINITE includepaths in c_cpp_properties.json, still, it keeps showing the message, although, I can find the file through "Go to Definition" option.
Is there any known solution to this?
It's not enough to configure VS Code includes, you need to pass those options to the compiler as well.
You don't mention your platform at all, so I'm going to use an example from my personal machine, a Macbook Pro with the fmt library.
When compiling with the fmt library, I have to provide three more options to the compiler.
-I/usr/local/include // Tells the compiler where to look for extra includes
-L/usr/local/lib // Tells the compiler where to look for extra libraries
-lfmt // fmt-specific command to use fmt library
So the full command ends up looking like this:
g++ -Wall -std=c++17 -I/user/local/include -L/usr/local/lib -lfmt main.cpp
I need all three options because fmt is installed in a non-standard location that the compiler doesn't check by default. According to the documentation, you can get away with just -lgmp and -lgmpxx if you installed the library in a standard location (happens by default with *nix and a package manager, I imagine).
If you use build tasks in VS Code, this can be set up and automated for you.

Mingw64 Linker error when trying to include -lhid [duplicate]

Context: I'm using Qt 5.9.3 on Windows, building for MinGW 32-bit. The Qt part is a side issue though - the problem seems to be with MinGW. The version of MinGW is 4.3.0, supplied prebuilt as part of the Qt installation.
I'm building a library which talks to a USB device over HID. Everything compiles fine, but it fails at the link stage with
./..\..\object\debug\usb_hid_device.o: In function `ZN8MyApp3USB5Win3213getDevicePathB5cxx11Ell':
<MYPATH>/../../source/win32/usb_hid_device.cpp:99: undefined reference to `HidD_GetAttributes(void*, _HIDD_ATTRIBUTES*)#8'
./..\..\object\debug\usb_hid_device.o: In function `ZN8MyApp3USB5Win3214CHIDDeviceImplC2EllRNS_15LogPerComponentE':
<MYPATH>/../../source/win32/usb_hid_device.cpp:200: undefined reference to `HidD_FlushQueue(void*)#4'
The linker command is
g++ -shared -mthreads -Wl,-subsystem,windows -Wl,--out-implib,<MYPATH>\bin\debug\libusb_hid_comms.a -o <MYPATH>\bin\debug\usb_hid_comms.dll object_script.usb_hid_comms.Debug -lhid -lsetupapi -LC:\Qt\Qt5.9.3\5.9.3\mingw53_32\lib C:\Qt\Qt5.9.3\5.9.3\mingw53_32\lib\libQt5Guid.a C:\Qt\Qt5.9.3\5.9.3\mingw53_32\lib\libQt5Cored.a
If I omit -lhid I get the same errors. I also get the same errors if I remove -lhid and explicitly set the path and filename to libhid.a. If I deliberately mistype the path and filename, it comes up with an error, so I know the command-line is getting parsed correctly. But for whatever reason, MinGW appears to not be linking with one of its own library files.
I've also tried removing -lsetupapi and I get the linker errors I'd expect for the functions defined in there. Likewise the Qt library files. But it seems that specifically for libhid.a, MinGW can see the library file but just isn't going to link with it.
Has anyone else seen this? Or can anyone else with the same (or similar) version of MinGW confirm or deny that they can link with libhid.a? Or is there something obviously wrong with what I'm doing?
I've just found the answer. I'm posting an answer myself so that other people know in future, because I think this is still a valid question which people might want to know about.
The problem is the include file hidsdi.h. The majority of other header files which pull in Win32 API calls have extern "C" around the function declarations. However this one doesn't! The result is that we end up with C++ name mangling for linker symbols, instead of the C-style "_" in front of the linker symbols.
The solution is to use
extern "C"
{
#include <hidsdi.h>
}
and then everything works fine.
The version of hidsdi.h with the older version of MinGW (which I'm porting from) did have that protection around the function declarations. However it looks like it's gone in the newer version.

Library not found for -lfl

I was using flex and bison to build a simple calculator project I cloned from Github.
But after I typed make in terminal, I got the following message:
gcc -o calc calc.tab.c lex.yy.c -lfl
calc.y:48:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main() {
^~~~
1 warning generated.
ld: library not found for -lfl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [calc] Error 1
How could I resolve this problem?
let me guess, trying to use flex on OS/X?
Try -ll instead of -lfl
Using Flex on OS/X
So yea, the flex library name on OS/X is just arbitrarily different for some reason. OS/X is not exactly Linux, but it's pretty close. You have some options here.
You can just simply have a separate build system and source files for OS/X. Certainly Apple might like that with their pushing XCode, objective-C and not much interoperability.
You can build vs Linux and then engage with Mac Ports and Homebrew.
You can create your project using autotools. That's not an awesome link, learning this system is rough going, but it's a standard thing for Linux for sure. This will actually work, I find if you have the patience for it, OS/X is close enough that autotools based builds will work on it.
Lately, I've been turned on to Cocoapods, which I believe to be an attempt to join the open source community and XCode. It's kind of half 1 and 3 sorta with an emphasis on modularizing the external source and getting it compiled into a .app (via Xcode).
warning: type specifier missing, defaults to 'int'
mean that you should declare return type for main function. Place int in function difinition.
ld: library not found for -lfl
flag -l mean that compiller must use libfl.a to build programm. As #waTeim said above, for Mac OS you can use libl.a instead, but this lib can be not exist alse. There is another way is to place
%option noyywrap
at the top of flex *.l file. In this case you can compile without additional libs.

Linking with .so files (webkit)

I'm trying to create a program that uses some of the code from WebKit/GTK+. Specifically, I want to load a string, use WebKit's parser to construct a DOM tree and then iterate over that tree.
I'm trying to use a class called HTMLDocument. WebKit/GTK+ doesn't expose this as part of its API and I'm running into some trouble linking against it.
I'm able to build WebKit/GTK+ normally, which gives me a file called: libwebkit-1.0.so. My program is:
#include <iostream>
#include <WebCore/config.h>
#include <WebCore/html/HTMLDocument.h>
using namespace WebCore;
int main() {
String title = "test";
RefPtr<HTMLDocument> d = HTMLDocument::create(0);
d->open();
d->write("<!doctype html><html><head><title>" + title + "</title></head><body></body></html>");
}
This compiles fine (I'm using the same include directives used by webkit to build), but results in linking errors.
...test_doc.cpp:18: undefined reference to `WebCore::String::String(char const*)'
...test_doc.cpp:21: undefined reference to WebCore::Document::open(WebCore::Document*)'
...(similar for every function I use)
If I run:
nm -C .libs/libwebkit-1.0.so | grep 'WebCore::Document::open'
I see:
003b1830 T WebCore::Document::open(WebCore::Document*)
which seems to indicate that the function is available. I have a reasonable amount of C++ experience, but not much experience with linking files under Linux.
I'm not expecting this exact problem to be solved, but I'm hoping someone can correct me if I have conceptual problems. My main question is why I see "undefined reference" errors when I'm linking with an .so file that lists that function as being defined. Is another file or build step needed?
Thank you very much.
Using:
Ubuntu 9.10
g++ 4.4.1
g++ is invoked with:
g++ --debug -DHAVE_CONFIG_H -I. `pkg-config --cflags libsoup-2.4` \
-DBUILDING_CAIRO__=1 -DBUILDING_GTK__=1 -DWTF_CHANGES -DWTF_USE_ICU_UNICODE=1 \
-DNDEBUG -I./WebCore -I./WebCore/accessibility -I./WebCore/bindings/js \
-I./WebCore/bridge -I./WebCore/bridge/c -I./WebCore/css -I./WebCore/dom \
...many more webkit include directories...
-DDATA_DIR=\"/usr/local/share\" \
test_doc.cpp -o test_doc.out \
./webkit-1.1.15.3/.libs/libwebkit-1.0.so
(I get the same result with -L/path/to/lib -lwebkit-1.0)
I think you might be running into an ordering problem: man g++ specifies that the order of the -l option is significant, and from memory the linker will only look for symbols in objects which have preceeded the current file on the command line.
I suspect what is happening is that the linker is trying to link test_doc before it's seen libwebkit-1.0.so, so it hasn't seen any of those symbols yet and bails.
You should use the -L/path/to/web and -lwebkit-1.0.
Also, I would compile your .cpp file in to a .o and then build your executable separately to make sure things are isolated.
Anyway, you may need to set your $LD_LIBRARY_PATH environment variable to include the path where that .so is stored. If you link to a shared library, you will need that library at run-time. Therefore, you do not want to have your webkit SO stored in its build directory (build/.libs). You want to install it. If you are not root, then you should ./configure with a --prefix=/some/path to install it to some local directory. Alternatively, you can link against the static library. One way to do this is to use the -bstatic (or similar) flag before your -lwebkit-1.0.
This is a good resource for Linux library creation and use.
I think you're issue is that the symbols you need are not exported. You can do objdump --dynamic-syms libwebkit-1.0.so to see which symbols are available. In the WebKit GTK build files there is use of the -fvisibility=hidden flag to restrict the symbols. Check your generated GNUMakefile and you'll see SYMBOL_VISIBILITY = -fvisibility=hidden. You should be able to modify the build files to get what you need.

Undefined symbol _main when trying to build logstalgia on mac

I have been trying to build the logstalgia project (http://code.google.com/p/logstalgia/) on my Mac (10.5). Rather than having to link it to the system libraries correctly, I have built and added all of the dependencies to the project. I am new at this, but I do think I have done this correctly, mostly because I have had two of my friends who are much more experienced say so.
Adding the frameworks removed all of the compile errors, but I still get a linker error. It seems to not be able to find the main() function. I have verified I included main.cpp in the sources to be compiled (using XCode) and that there are no accidental double declarations. I have also verified that the main function is correctly declared (no missing brackets, etc).
It is as though XCode does not link in the correct order. Any help would be really appreciated, I am really excited to be down to a single error! (Hope fixing this does not open a floodgate).
Thanks,
Hamilton
PS - I can definitely provide a zip of the Xcode project if anyone is willing to look!
Checking Dependencies
Ld "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug/Untitled" normal i386
cd "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled"
setenv MACOSX_DEPLOYMENT_TARGET 10.5
/developer/usr/bin/g++-4.0 -arch i386 -isysroot /developer/SDKs/MacOSX10.5.sdk "-L/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug" -L/sw/lib "-L/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/../../pcre-7.9/.libs" -L/opt/local/lib -L/sw/lib "-F/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug" -F/Users/hamiltont/Downloads/logstalgia-0.9.2 -F2/src/SDL.framework "-F/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled" -filelist "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Untitled.build/Debug/Untitled.build/Objects-normal/i386/Untitled.LinkFileList" -mmacosx-version-min=10.5 -framework OpenGL -lpcre -lSDL -lSDL_image-1.2.0 -prebind -o "/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Debug/Untitled"
Undefined symbols:
"_main", referenced from:
start in crt1.10.5.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
I got this error to go away. If I understand, essentially SDL re-names the main function, so that it can do some stuff, then run your application, then clean up. Turns out that if you are building in Xcode, you must use ObjectiveC to compile your application.
In Xcode, telling the linker to try and use SDL_main(), rather than just main() does not work (for some technical reasons that are a bit beyond me). So, you include a few Objective C files. In Oc, you get the benefit of being able to say explicitely what the name of your main class is. Hence, the Objective C files you include seem to do nothing more than let Xcode know to look for SDL_main().
In summary, this really had nothing to do with Logstalgia, but was entirely a problem with getting SDL to link correctly in Xcode. This link is talking about this problem exactly. The SDLMain.h and SDLMain.m are Objective C files. If you can't find them, try googleing "Setting up SDL templates in Xcode." I installed the templates in Xcode, used one of them to create an empty project that would compile, link, and run (and promptly do nothing!) and then I added the project files I wanted to the pre-configured project.
Thanks!
Double-check the link file list to make sure main.cpp's object file is present there:
/Users/hamiltont/Downloads/logstalgia-0.9.2 2/Untitled/build/Untitled.build/Debug/Untitled.build/Objects-normal/i386/Untitled.LinkFileList
You might also want to preprocess the main.cpp to make sure main isn't getting inadvertently renamed (via a rogue macro) or omitted (via a rogue #if).