Undefined reference to 'SDL_main' - c++

I've recently decided to try working with SDL with CodeBlocks 10.05. I started with the tutorial on http://www.sdltutorials.com/sdl-tutorial-basics and did my best to follow it. Unfortunately, I'm encountering:
..\..\..\..\..\..\SDL\SDL-1.2.15\lib\libSDLmain.a(SDL_win32_main.o):SDL_win32_main.c|| undefined reference to `SDL_main'|
when I try to compile it.
I've searched through many of the questions on this website and other tutorials (mainly the tutorial on LazyFoo and the CodeBlocks wiki) and can't seem to find a solution.
C:\SDL\SDL-1.2.15\include has been added in the Compiler tab (Search Directories)
C:\SDL\SDL-1.2.15\lib has been added in the Linker tab
The libraries libmingw32.a, libSDLmain.a, libSDL.dll.a are linked in that order
libmingw32.a from the MinGW\lib folder in the CodeBlocks installation directory
SDL.dll is in both the System32 folder and in the project folder
When attempting to follow the tutorial on the CodeBlocks wiki, I was told that SDL.h could not be found in the given directory (when making a new SDL project).
CApp.cpp
#include "CApp.h"
#include "SDL\SDL.h"
CApp::CApp(){
Surf_Display=NULL;
Running=true;
}
int CApp::OnExecute(){
if (OnInit()==false){
return -1;
}
SDL_Event Event;
while (Running){
while (SDL_PollEvent(&Event)){
OnEvent(&Event);
}
OnLoop();
OnRender();
}
OnCleanup();
return 0;
}
int main(int argc, char* argv[]){
CApp theApp;
return theApp.OnExecute();
}
CApp.h
#ifndef CAPP_H_INCLUDED
#define CAPP_H_INCLUDED
#include "SDL\SDL.h"
class CApp{
private:
bool Running;
SDL_Surface* Surf_Display;
public:
CApp();
int OnExecute();
public:
bool OnInit();
void OnEvent(SDL_Event* Event);
void OnLoop();
void OnRender();
void OnCleanup();
};
#endif // CAPP_H_INCLUDED

put these arguments to the main function. I had this problem too, and I fixed it few seconds ago.
int main(int argv, char** args)
{
}

Try #undef main after all SDL related headers.
Update. This is not a valid solution!
As pointed out by HolyBlackCat, this is a pretty sloppy fix. SDL replaces the main function in order to perform some initialization and/or cleanup that is otherwise not possible, and then calls back to the actual user function.
The interception works by replacing the name of user's main function to SDL_main, with a simple macro
#define main SDL_main
The user's function then ceases to be the entry point for the application, and an entry point provided by SDL is used. The proposed #undef disables the interception recklessly and one should argue that it is not supposed to work at all. For those who successfully compiled and ran an SDL application after this "fix", it must have simply been a platform-dependent coincidence.
The proper solution to the OP's error is making sure that the file containing main gets compiled and linked, and that the function has correct signature. As already posted by others.

The only plausible reason for your problem I can think of is that when you created the file with main in it, you forgot to add it to build targets.
You should see CApp.cpp in the list where my main.cpp is. Right click on it and click Properties. Click on Build tab in the window that pops up. You should see this:
Click OK, hit Ctrl+F11 (Rebuild).
Good luck.

Recently, I had this problem, watched some YouTube videos and also followed the installation guide by LazyFoo and I kept getting the "Undefined reference to SDL_main" error.
I followed everything said here after successfully linking the minGw files to my project properties, but it didn't work until I added to my main function int main (int argv, char** args) and voila, it worked.
using namespace std;
int main(int argv, char** args) { if(SDL_Init(SDL_INIT_VIDEO)<0) {
cout<<"Endl Init Failed."<<endl;
return 1; }
cout<<"SDL Init succeeded."<<endl;
SDL_Quit(); return 0; }
Why it worked is still not clear to me but it worked anyway.

Define SDL_MAIN_HANDLED before you include the SDL libs:
#define SDL_MAIN_HANDLED
#include <GL/glew.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
More info: I'm using the SDL functions without the SDL_main be defined. Is that fine?

This was the first question that pop out to my search.
None of the solutions worked for me.
Eventually I figured it what worked for me. Will post the my answer here to "any fellow wanderer".
My problem was that I tried to compile some old C game not a C++ one.
One part of the solution for me was to rename the main.c to main.cpp
And then to signal to CMake to use CPP compiler for all C files.
Eventually here is a portion of my CMakeLists.txt:
# set minimum cmake version
cmake_minimum_required(VERSION 3.19 FATAL_ERROR)
# project name and language
project(FootballManager LANGUAGES CXX)
# This is mandatory too, because otherwise they are not compiled an linked.
file(GLOB_RECURSE CFILES "${CMAKE_SOURCE_DIR}/*.c")
SET_SOURCE_FILES_PROPERTIES(${CFILES} PROPERTIES LANGUAGE CXX)
# list sources
list(APPEND _sources config.h)
# ... removed some of the other sources for brevity ...
list(APPEND _sources misc.c)
# Link SDL, yes this is SDL1.2
find_package(SDL REQUIRED)
include_directories(FootballManager ${SDL_INCLUDE_DIRS})
add_executable(fm main.cpp ${_sources})
target_link_libraries(fm ${SDL_LIBRARIES})

Related

How to include jxcore c++ library "jx.h" in qt applications?

This is the sample code I am trying execute in Qt Creator. I have included all the JX libraries in Qt. The JX c++ code works outside Qt well but I want to make it work inside Qt. Please review the code and suggest me a way to achieve this.
Currently I am getting errors such as "undefined reference to `v8::Locker::Locker(v8::Isolate*)'" and 1000 similar errors. I gues its because qt is not recognizing the JX libraries.
Thanks in advance.
#include "mainwindow.h"
#include <QApplication>
#include "jx.h"
#if defined(_MSC_VER)
// Sleep time for Windows is 1 ms while it's 1 ns for POSIX
// Beware using this for your app. This is just to give a
// basic idea on usage
#include <windows.h>
#else
#include <unistd.h>
#define Sleep(x) usleep(x)
#endif
void callback(JXValue *results, int argc) {
// do nothing
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
const char *contents =
"process.requireGlobal = require;";
JX_Initialize(argv[0], callback);
JX_InitializeNewEngine();
JX_DefineMainFile(contents);
JX_StartEngine();
JXValue ret_val;
JX_Evaluate("process.requireGlobal('./dummy.js').data",
"eval",&ret_val);
while (JX_LoopOnce() != 0) usleep(1);
JX_Free(&ret_val);
JX_StopEngine();
return a.exec();
}
Yes, the 'undefined reference to' is a linker error.
This is due to the fact that the linker can't find the library (libraries) in the paths it already has, so you need to specified it (them) and you've to do it in the .pro file of your Qt project.
.pro file works similarly to makefile: here you have to specify "extra" paths where source and header files are located, as well as libraries.
For your specific question, you need to add all the library requesting to make jxcore working, adding them to the keyword "LIBS": -L introduce path(s) at which libraries are stored, while -l introduce libraries themselves you want to use. I.e.
LIBS += -L/path/to/your/libraries \
-lname_of_library_without_lib
You can find more detailed description at this link http://doc.qt.io/qt-4.8/qmake-project-files.html
Go directly to last section if you're just interested in how add libraries
Hope it helps

SFML 2.1 Networking

I was trying to follow this tutorial, and I got this far.
#include <SFML/Network.hpp>
#include <SFML/System.hpp>
#include <iostream>
using namespace std;
int main(){
sf::IpAddress ip=sf::IpAddress::getLocalAddress();
sf::TcpSocket socket;
char connectiontype,mode;
char buffer[2000];
size_t received;
cout<<"s for server, c for client"<<endl;
cin>>connectiontype;
string text="connected to ";
if(connectiontype=='s'){
sf::TcpListener listener;
listener.listen(3000);
listener.accept(socket);
text+="server";
mode='s';
}
else if(connectiontype=='c'){
socket.connect(ip,3000);
text+="client";
mode='r';
}
socket.send(text.c_str(),text.length()+1);
socket.receive(buffer,sizeof(buffer),received);
cout<<buffer<<endl;
bool done=false;
while(!done){
if(mode=='s'){
getline(cin,text);
socket.send(text.c_str(),text.length()+1);
mode='r';
}
else if(mode=='r'){
socket.receive(buffer,sizeof(buffer),received);
if(received>0){
cout<<"received: "<<buffer<<endl;
mode='s';
}
}
}
return 0;
}
I compiled it, and got these errors:
I also tried adding sfml-network-2.dll and sfml-network-d-2.dll into my project folder, but it didn't work.
I'm also pretty sure that I set everything up correctly.
This is my setup:
I covered my name up, if you don't mind. Thanks!
Update:
I have reinstalled SFML, and I updated my code and my errors.
I solved my problem!
I changed each library to just the name, not where it is.
Example: Desktop/SFML-2.1/lib/libsfml-network-s-d.a->sfml-network
If you are pretty sure you have set up everything correctly, are you sure you added the SFML path to the Compiler include paths AND the SFML DLL to the Linker paths?
As you use Code::Blocks, have you setup your project "online game" exactly as described here?
http://www.sfml-dev.org/tutorials/2.1/start-cb.php
Update:
Have a look at this picture:
http://www.sfml-dev.org/tutorials/2.1/images/start-cb-link-libs.png
Are you sure, you've got sfml-network in the library list there? This might be the problem.
Adding the dlls to the project folder won't help, as it is a compiler/linker error and not a runtime library error.
You need to link to sfml-system too.
As a side note, you can find the official example about sockets here.

How to run a simple cpp file that requires QT?

I have QT 5.1.1 installed on my machine, but I'm having some troubles using it. I'm trying to run the following simple program that requires QT:
//Playing Video
#include "cv.h"
#include "opencv2\objdetect\objdetect.hpp"
#include "opencv2\core\core.hpp"
#include "opencv2\highgui\highgui.hpp"
#include "opencv2\features2d\features2d.hpp"
#include "opencv2\calib3d\calib3d.hpp"
#include "opencv2\nonfree\nonfree.hpp"
#include "highgui.h"
#include <openbr\openbr_plugin.h>
using namespace cv;
static void printTemplate(const br::Template &t)
{
const QPoint firstEye = t.file.get<QPoint>("Affine_0");
const QPoint secondEye = t.file.get<QPoint>("Affine_1");
printf("%s eyes: (%d, %d) (%d, %d)\n", qPrintable(t.file.fileName()), firstEye.x(), firstEye.y(), secondEye.x(), secondEye.y());
}
int main(int argc, char *argv[])
{
br::Context::initialize(argc, argv);
// Retrieve classes for enrolling and comparing templates using the FaceRecognition algorithm
QSharedPointer<br::Transform> transform = br::Transform::fromAlgorithm("FaceRecognition");
QSharedPointer<br::Distance> distance = br::Distance::fromAlgorithm("FaceRecognition");
// Initialize templates
br::Template queryA("../data/MEDS/img/S354-01-t10_01.jpg");
br::Template queryB("../data/MEDS/img/S382-08-t10_01.jpg");
br::Template target("../data/MEDS/img/S354-02-t10_01.jpg");
// Enroll templates
queryA >> *transform;
queryB >> *transform;
target >> *transform;
printTemplate(queryA);
printTemplate(queryB);
printTemplate(target);
// Compare templates
float comparisonA = distance->compare(target, queryA);
float comparisonB = distance->compare(target, queryB);
// Scores range from 0 to 1 and represent match probability
printf("Genuine match score: %.3f\n", comparisonA);
printf("Impostor match score: %.3f\n", comparisonB);
br::Context::finalize();
return 0;
}
It also requires OpenCV 2.4.6.1 and OpenBR, but that's not the problem.
All the definitions (variables and functions) in the above code that are related to QT are undefined. I've tried to find the relevant h files in QT folder and to include them, but that did not succeed since I couldn't fine qtcore.h (but a different file named qtcore with lot's of includes that I don't now how to use). I've tried to add QT "include" directory under "additional include directories" in the project properties but that didn't work either. I've also tried to add QT "lib" folder under "additional library directories" but that also did not work.
Basically, I tried everything I could think of. Can someone please explain how to I use those QT definitions? I'm really stuck and I could use any help given.
Thanks,
Gil.
(Optional) Update to Qt 5.2.
Start Qt Creator.
Create a new Qt Widgets Application project. You can give the class/files random names, it doesn't matter. Uncheck the "generate form" option, as you don't need any forms.
Remove all the files other than main.cpp from the project. You do this by right-clicking on them in the project tree on the left and choosing Remove File.
Copy-paste your code into main cpp. Make sure you completely replace main.cpp's contents, the default contents shouldn't be there anymore.
Add the opencv library to the project. Right-click on the project's root, select "Add Library", and go from there.
Re-run qmake by right-clicking on the project root and selecting "Run qmake".
Build and run the project by pressing Ctrl-R (Cmd-R on mac).
Qt uses a (non-standard) custom toolchain that has to run before the Qt-dependent code can be compiled. I've never tried using Qt outside of QtCreator, but if you really need Qt I'd suggest you use the QtCreator IDE; if you're not using it already of course. It's a very decent IDE, even for non-Qt projects.
Also, if you haven't done so already, make sure the Qt SDK is installed; the headers alone are not enough. QtCreator by itself is also not enough, you'll need the SDK. If you don't feel like doing so, my suggestion would be to look at Poco. It's not a 1:1 replacement for Qt, but a very mature framework nevertheless.

Code::Blocks, MinGW, libsdl, and GNU C++ compiler: undefined reference to `WinMain#16

I have been trying to compile the most basic SDL application, but no matter what I do I keep getting this error:
c:/program files (x86)/codeblocks/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined reference to `WinMain#16'
I searched for solutions for this, but they all had to do with either Visual C++ or a missing main. I am not using Visual C++, and I have defined main.
Here's my code:
#include "SDL/SDL.h"
int main( int argc, char* args[] )
{
//Start SDL
SDL_Init( SDL_INIT_EVERYTHING );
//Quit SDL
SDL_Quit();
return 0;
}
Don't use "Other linker options". Use the "Link libraries" section. Add the following items.
mingw32
SDLmain
SDL
You can put -mwindows in the "Other linker options" section.
In case someone else comes across this, I put -lmingw32 after -lSDLmain and -lSDL which caused this issue for me. Putting -lmingw32 first fixed it.
I encountered the same error in a project of mine that I want to compile both on linux and windows.
I use a makefile to compile the project.
A solution that has worked for me, although I admit it is a bit of a hack is adding this to main.cpp (wherever your main function would be)
extern "C" {
int WinMain(int argc, char** argv)
{
return main(argc, argv);
}
}
This makes the linker find WinMain and use it as the entry point in the program. I can also hope that this solution doesn't break linux compilability, hopefully it will be considered just an unused function.

Linking Qt in CodeLite

I'm not sure why this is, but 99% of the problems I have with programming in C++ have to do with the gcc linker.
I want to link the Qt library to a project in CodeLite. This is the code I have so far:
#include <QApplication>
int main(int argc, char *argv[])
{
return 0;
}
When I compile, I get the error
/Users/andrew/Dev/C++/COSC 102/elitecod/main.cpp:1:24: error: QApplication: No such file or directory
I have Qt installed (with Homebrew, Mac OS X Lion) in /usr/local/include. Why is this happening, and how can I fix this problem?
The error indicates it can't find the file QApplication. You need to add the Qt 'include' directory to the list of places the compiler should look for it and other header files.
A brief google seems to indicate you may have other problems with Qt, you might want to keep this link handy.