Multiple undefined reference errors when linking freeglut and codelite (minGW32 c++) - c++

While trying to install (if that's the right word) opengl onto my codelite IDE to create c++ opengl programs, I have run into multiple undefined reference errors in the freeglut_std.h file as well as well known functions like glutMainLoop() are also "undefined".
So I have actually found the function definitions in the freeglut_std.h file and I have tried messing with the header file to make sure that there is no false conditions causing my definitions not to be created. (like making #if true ..... #endif (so that the code will for sure run)). I have experience in C but have never linked files like this before. Going through several webpages like: https://www.ntu.edu.sg/home/ehchua/programming/opengl/HowTo_OpenGL_C.html , https://www.transmissionzero.co.uk/computing/using-glut-with-mingw/ I linked my files. (Also note, that this question has been asked before however most posts had different solutions that didn't work for me)
So here is how codelite is compling my files (with not erroneous code) :
C:/mingw-w64/i686-7.3.0-posix-dwarf-rt_v5-rev0/mingw32/bin/g++.exe -c "C:/Users/admin/Documents/codelite/workspaces/c_plus_plus/cpp_openGL/main.cpp" -g -O0 -Wall -I"C:\mingw-w64\i686-7.3.0-posix-dwarf-rt_v5-rev0\mingw32\include" -o ./Debug/main.cpp.o -I. -I.
C:/mingw-w64/i686-7.3.0-posix-dwarf-rt_v5-rev0/mingw32/bin/g++.exe -o ./Debug/cpp_openGL #"cpp_openGL.txt" -L. -m32 -static-libgcc -static-libstdc++ -static -lpthread -L"C:\mingw-w64\i686-7.3.0-posix-dwarf-rt_v5-rev0\mingw32\lib" -Wl,--subsystem,windows -lfreeglut -lopengl32 -lglu32
mingw32-make.exe[1]: Leaving directory 'C:/Users/admin/Documents/codelite/workspaces/c_plus_plus/cpp_openGL'
====0 errors, 0 warnings====
However for something like this (actual test code):
/*
* GL01Hello.cpp: Test OpenGL C/C++ Setup
*/
#include <windows.h> // For MS Windows
#include <GL/glut.h> // GLUT, includes glu.h and gl.h
/* Handler for window-repaint event. Call back when the window first appears and
whenever the window needs to be re-painted. */
void display() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
// Draw a Red 1x1 Square centered at origin
glBegin(GL_QUADS); // Each set of 4 vertices form a quad
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex2f(-0.5f, -0.5f); // x, y
glVertex2f( 0.5f, -0.5f);
glVertex2f( 0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
glFlush(); // Render now
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char** argv) {
glutInit(&argc, argv); // Initialize GLUT
glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
glutInitWindowSize(320, 320); // Set the window's initial width & height
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
glutDisplayFunc(display); // Register display callback handler for window re-paint
glutMainLoop(); // Enter the infinitely event-processing loop
return 0;
}
I get the following errors:
./Debug/main.cpp.o: In function `glutInit_ATEXIT_HACK':
C:/mingw-w64/i686-7.3.0-posix-dwarf-rt_v5-rev0/mingw32/include/GL/freeglut_std.h:623: undefined reference to `_imp____glutInitWithExit#12'
./Debug/main.cpp.o: In function `glutCreateWindow_ATEXIT_HACK':
C:/mingw-w64/i686-7.3.0-posix-dwarf-rt_v5-rev0/mingw32/include/GL/freeglut_std.h:625: undefined reference to `_imp____glutCreateWindowWithExit#8'
./Debug/main.cpp.o: In function `glutCreateMenu_ATEXIT_HACK':
C:/mingw-w64/i686-7.3.0-posix-dwarf-rt_v5-rev0/mingw32/include/GL/freeglut_std.h:627: undefined reference to `_imp____glutCreateMenuWithExit#8'
./Debug/main.cpp.o: In function `main':
C:/Users/admin/Documents/codelite/workspaces/c_plus_plus/cpp_openGL/main.cpp:32: undefined reference to `_imp__glutInitWindowSize#8'
C:/Users/admin/Documents/codelite/workspaces/c_plus_plus/cpp_openGL/main.cpp:33: undefined reference to `_imp__glutInitWindowPosition#8'
C:/Users/admin/Documents/codelite/workspaces/c_plus_plus/cpp_openGL/main.cpp:34: undefined reference to `_imp__glutDisplayFunc#4'
C:/Users/admin/Documents/codelite/workspaces/c_plus_plus/cpp_openGL/main.cpp:35: undefined reference to `_imp__glutMainLoop#0'
collect2.exe: error: ld returned 1 exit status
====7 errors, 0 warnings====
The file that it is complain about is freeglut_std.h, the following is copied from the file:
#if defined(_WIN32) && !defined(GLUT_DISABLE_ATEXIT_HACK) && !defined(__WATCOMC__)
FGAPI void FGAPIENTRY __glutInitWithExit(int *argcp, char **argv, void (__cdecl *exitfunc)(int));
FGAPI int FGAPIENTRY __glutCreateWindowWithExit(const char *title, void (__cdecl *exitfunc)(int));
FGAPI int FGAPIENTRY __glutCreateMenuWithExit(void (* func)(int), void (__cdecl *exitfunc)(int));
#ifndef FREEGLUT_BUILDING_LIB
#if defined(__GNUC__)
#define FGUNUSED __attribute__((unused))
#else
#define FGUNUSED
#endif
static void FGAPIENTRY FGUNUSED glutInit_ATEXIT_HACK(int *argcp, char **argv) { __glutInitWithExit(argcp, argv, exit); }//<--has problem with
#define glutInit glutInit_ATEXIT_HACK
static int FGAPIENTRY FGUNUSED glutCreateWindow_ATEXIT_HACK(const char *title) { return __glutCreateWindowWithExit(title, exit); }//<--has problem with
#define glutCreateWindow glutCreateWindow_ATEXIT_HACK
static int FGAPIENTRY FGUNUSED glutCreateMenu_ATEXIT_HACK(void (* func)(int)) { return __glutCreateMenuWithExit(func, exit); } //<--has problem with
#define glutCreateMenu glutCreateMenu_ATEXIT_HACK
#endif
#endif
#ifdef __cplusplus
}
#endif
Note that I could get rid the 3-undefined references with:
#define GLUT_DISABLE_ATEXIT_HACK
However the remaining errors still exist.
A final note in freeglut_std.h the following lines exist (are these not definitions)
FGAPI void FGAPIENTRY glutInit( int* pargc, char** argv );
FGAPI void FGAPIENTRY glutInitWindowPosition( int x, int y );
FGAPI void FGAPIENTRY glutInitWindowSize( int width, int height );
FGAPI void FGAPIENTRY glutInitDisplayMode( unsigned int displayMode );
FGAPI void FGAPIENTRY glutInitDisplayString( const char* displayMode );
And something must be working since it doesn't complain about
glutinit(param...)
glutCreateWindow(param...)
UPDATE
I should let you guys know that I have a freeglut.dll file saved in the same location as my application. However that shouldn't matter because I also tried a static build white I used -DFREEGLUT_STATIC in the complier command, and linked -lfreeglut_static This had the same result, except the _imp_ part of the error was gone.
So in short I am bamboozled here, Any help is always greatly appreciated.
(p.s. please spare me mods).

Related

`make` compilation for OpenGL works on VSCode's terminal, but gives `symbol(s) not found for architecture x86_64` on regular terminal (macOS M1)

OS: macOS Ventura version 13.1, on M1.
I'm compiling a simple OpenGL program. I have a makefile as shown below:
CXX = clang++
CXXFLAGS = -I/opt/homebrew/Cellar/glew/2.2.0_1/include -L/opt/homebrew/Cellar/glew/2.2.0_1/lib -w
LIBS = -lGLEW.2.2.0 -framework OpenGL -framework GLUT
SOURCES = t2.cpp
OBJ = $(SOURCES:.cpp=.o)
TARGETS = $(SOURCES:.cpp=)
all: $(TARGETS)
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $# $<
$(TARGETS): %: %.o
$(CXX) $(CXXFLAGS) -o $# $< $(LIBS)
clean:
rm -f $(OBJ) $(TARGETS) *.o
.PHONY: all clean
My simple t2.cpp:
#include <iostream>
#include <GL/glew.h>
#include <GLUT/glut.h>
void resizeCB(int width, int height)
{
/* use the full view port */
glViewport(0, 0, width, height);
/* use 2D orthographic parallel projection */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, width, 0.0, height);
}
typedef struct point2D
{
int x;
int y;
} Point2D;
Point2D roof[3];
Point2D house[4];
void initGeom()
{
// initialize the roof
roof[0].x = 270;
roof[0].y = 340;
roof[1].x = 450;
roof[1].y = 340;
roof[2].x = 360;
roof[2].y = 400;
house[0].x = 285;
house[0].y = 270;
house[1].x = 435;
house[1].y = 270;
house[2].x = 435;
house[2].y = 340;
house[3].x = 285;
house[3].y = 340;
}
// clear the window and fill it with white colour
// set up gl colour to white
void renderCB()
{
// glClearColor(1.0, 1.0, 1.0, 0.0);
// clearing up the canvas with the specific colour
initGeom();
glClear(GL_COLOR_BUFFER_BIT);
// swap the buffers (using double buffers
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_TRIANGLES);
for (int i = 0; i < 3; ++i)
{
glVertex2iv((GLint *)&roof[i]);
}
glEnd();
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_POLYGON);
for (int i = 0; i < 4; ++i)
{
glVertex2iv((GLint *)&house[i]);
}
glEnd();
glFlush();
glutSwapBuffers();
// return;
}
int main(int argc, char **argv)
{
int winId;
// initialize GLUT and pass it the command variables
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowSize(1024, 768);
glutInitWindowPosition(100, 100);
winId = glutCreateWindow("Tutorial 02");
GLenum res = glewInit();
if (res != GLEW_OK)
{
printf("Error - %s \n", glewGetErrorString(res));
return (-1);
}
// print OpenGL information
printf("Renderer: %s \n", glGetString(GL_RENDERER));
printf("OpenGL version: %s \n", glGetString(GL_VERSION));
printf("OpenGL shading language version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
glutReshapeFunc(resizeCB);
glutDisplayFunc(renderCB);
glutMainLoop();
return (0);
}
I've noticed that when I compile via make on VSCode's integrated terminal, it works, output:
clang++ -I/opt/homebrew/Cellar/glew/2.2.0_1/include -L/opt/homebrew/Cellar/glew/2.2.0_1/lib -w -c -o t2.o t2.cpp
clang++ -I/opt/homebrew/Cellar/glew/2.2.0_1/include -L/opt/homebrew/Cellar/glew/2.2.0_1/lib -w -o t2 t2.o -lGLEW.2.2.0 -framework OpenGL -framework GLUT
But, when I compile via make on a regular terminal, I get this:
clang++ -I/opt/homebrew/Cellar/glew/2.2.0_1/include -L/opt/homebrew/Cellar/glew/2.2.0_1/lib -w -c -o t2.o t2.cpp
clang++ -I/opt/homebrew/Cellar/glew/2.2.0_1/include -L/opt/homebrew/Cellar/glew/2.2.0_1/lib -w -o t2 t2.o -lGLEW.2.2.0 -framework OpenGL -framework GLUT
Undefined symbols for architecture x86_64:
"_glewGetErrorString", referenced from:
_main in t2.o
"_glewInit", referenced from:
_main in t2.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [t2] Error 1
I'm honestly stumped as to why. I've restarted my computer, and now everything works as expected. WHAT???
I mean, I was expecting make to be deterministic across both terminals. I can't say I've tried anything meaningful aside from restarting my computer, I'm quite confused as to discrepancies -- this is probably the first I've encountered such a bug. I'm not sure if I'll encounter such a bug again, but I do not want to restart my computer as a fix -- and I want to understand why this is happening.
My best (terrible) guess has something to do with VSCode's terminal makefile invoking the arm64-apple-darwin<version> clang++ binary, but the regular terminal's makefile invoked the x86_64-apple-darwin<version> clang++ binary.
But I can't for the life of me figure out why, as the makefile does not ever specify the architecture, and would assume the default (ARM).
I want to get to the bottom of this, this is one really interesting bug. Any help appreciated. Thanks!

Many undefined references with CLion C++ [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
How add OpenGL & GLUT for CLion on Windows?
(1 answer)
Closed 1 year ago.
I want to learn how to use the OpenGL library with C++ but I am struggling getting the external libraries to import. I am using CLion as my IDE and MinGW as my compiler. Here is my CMake code:
cmake_minimum_required(VERSION 3.17)
project(compgeo)
set(CMAKE_CXX_STANDARD 14)
add_executable(compgeo main.cpp)
find_package(GLUT REQUIRED)
find_package(OpenGL REQUIRED)
include_directories( ${OPENGL_INCLUDE_DIRS} ${GLUT_INCLUDE_DIRS} )
And here is my code that I am trying to test:
/*
* GL01Hello.cpp: Test OpenGL C/C++ Setup
*/
#include <windows.h> // For MS Windows
#include <GL/glut.h> // GLUT, includes glu.h and gl.h
/* Handler for window-repaint event. Call back when the window first appears and
whenever the window needs to be re-painted. */
void display() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
// Draw a Red 1x1 Square centered at origin
glBegin(GL_QUADS); // Each set of 4 vertices form a quad
glColor3f(1.0f, 0.0f, 0.0f); // Red
glVertex2f(-0.5f, -0.5f); // x, y
glVertex2f( 0.5f, -0.5f);
glVertex2f( 0.5f, 0.5f);
glVertex2f(-0.5f, 0.5f);
glEnd();
glFlush(); // Render now
}
/* Main function: GLUT runs as a console application starting at main() */
int main(int argc, char** argv) {
glutInit(&argc, argv); // Initialize GLUT
glutCreateWindow("OpenGL Setup Test"); // Create a window with the given title
glutInitWindowSize(320, 320); // Set the window's initial width & height
glutInitWindowPosition(50, 50); // Position the window's initial top-left corner
glutDisplayFunc(display); // Register display callback handler for window re-paint
glutMainLoop(); // Enter the infinitely event-processing loop
return 0;
}
These are the errors I am getting. The issue comes around once it links the CXX executable:
[ 50%] Linking CXX executable compgeo.exe
CMakeFiles\compgeo.dir/objects.a(main.cpp.obj): In function `glutInit_ATEXIT_HACK':
c:/mingw/include/gl/glut.h:486: undefined reference to `__glutInitWithExit#12'
CMakeFiles\compgeo.dir/objects.a(main.cpp.obj): In function `glutCreateWindow_ATEXIT_HACK':
c:/mingw/include/gl/glut.h:503: undefined reference to `__glutCreateWindowWithExit#8'
CMakeFiles\compgeo.dir/objects.a(main.cpp.obj): In function `glutCreateMenu_ATEXIT_HACK':
c:/mingw/include/gl/glut.h:549: undefined reference to `__glutCreateMenuWithExit#8'
CMakeFiles\compgeo.dir/objects.a(main.cpp.obj): In function `Z7displayv':
A:/CppProjects/compgeo/main.cpp:10: undefined reference to `glClearColor#16'
A:/CppProjects/compgeo/main.cpp:11: undefined reference to `glClear#4'
A:/CppProjects/compgeo/main.cpp:14: undefined reference to `glBegin#4'
A:/CppProjects/compgeo/main.cpp:15: undefined reference to `glColor3f#12'
A:/CppProjects/compgeo/main.cpp:16: undefined reference to `glVertex2f#8'
A:/CppProjects/compgeo/main.cpp:17: undefined reference to `glVertex2f#8'
A:/CppProjects/compgeo/main.cpp:18: undefined reference to `glVertex2f#8'
A:/CppProjects/compgeo/main.cpp:19: undefined reference to `glVertex2f#8'
A:/CppProjects/compgeo/main.cpp:20: undefined reference to `glEnd#0'
A:/CppProjects/compgeo/main.cpp:22: undefined reference to `glFlush#0'
CMakeFiles\compgeo.dir/objects.a(main.cpp.obj): In function `main':
A:/CppProjects/compgeo/main.cpp:29: undefined reference to `glutInitWindowSize#8'
A:/CppProjects/compgeo/main.cpp:30: undefined reference to `glutInitWindowPosition#8'
A:/CppProjects/compgeo/main.cpp:31: undefined reference to `glutDisplayFunc#4'
A:/CppProjects/compgeo/main.cpp:32: undefined reference to `glutMainLoop#0'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [compgeo.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/compgeo.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles/compgeo.dir/rule] Error 2
mingw32-make.exe: *** [compgeo] Error 2
CMakeFiles\compgeo.dir\build.make:104: recipe for target 'compgeo.exe' failed
CMakeFiles\Makefile2:94: recipe for target 'CMakeFiles/compgeo.dir/all' failed
CMakeFiles\Makefile2:101: recipe for target 'CMakeFiles/compgeo.dir/rule' failed
Makefile:137: recipe for target 'compgeo' failed
You must add the library as a link dependency.
target_link_libraries(compgeo ${OPENGL_LIBRARIES} ${GLUT_LIBRARY} )

OpenGL program failing to link?

I'm attempting to use the GA Sandbox source code found here on Linux (specifically Ubuntu 16.04). Yet when it comes to compiling the first example I'm left with this error.
g++ -g -O2 -o chap1ex1 chap1ex1.o -lGL -lGLU -lglut ../../libgasandbox/libgasandbox.a
../../libgasandbox/libgasandbox.a(libgasandbox_a-gl_util.o): In function
`pickLoadMatrix()':
/mnt/c/GASandbox/ga_sandbox-1.0.7/libgasandbox/gl_util.cpp:231: undefined
reference to `gluPickMatrix'
collect2: error: ld returned 1 exit status
Makefile:216: recipe for target 'chap1ex1' failed
I should mention that the configure script which provided the Makefile mentioned above does not initially link either -lGL or -lGLU. This gave me an error pertaining to a missing DSO, which was corrected by linking -lGL. I then wound up with this error. I looked around for any similar errors online and found this post, where the OP solved it by linking -lGLU. I was not so fortunate.
Here is the snippet of code in question, from gl_util.cpp.
#include <string>
#include "gl_util.h"
#if defined (__APPLE__) || defined (OSX)
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
// code inbetween
namespace GLpick {
bool g_pickActive = false;
int g_OpenGL_pick[4] = {0, 0, 0, 0};
double g_frustumNear = 1.0;
double g_frustumFar = 100.0;
double g_frustumWidth = -1.0;
double g_frustumHeight = -1.0;
int g_pickWinSize = 4;
}
void pickLoadMatrix() {
if (!GLpick::g_pickActive) return;
GLint viewport[4];
glGetIntegerv(GL_VIEWPORT, viewport);
gluPickMatrix(
GLpick::g_OpenGL_pick[0], GLpick::g_OpenGL_pick[1],
GLpick::g_OpenGL_pick[2] * 2 + 1, GLpick::g_OpenGL_pick[3] * 2 + 1,
viewport);
}
In glu.h, gluPickMatrix()'s signature is GLAPI void GLAPIENTRY gluPickMatrix (GLdouble x, GLdouble y, GLdouble delX, GLdouble delY, GLint *viewport);. So, I attempted to change int g_OpenGL_pick[] = {0, 0, 0, 0}; to GLdouble g_OpenGL_pick[] = {0.0, 0.0, 0.0, 0.0};. Neither that nor casting the individual values to GLdouble worked.
What might I be overlooking? Or are there any concepts that could help narrow down my search?
Try moving the libgasandbox.a before all the -l options on the command line. So your command would look like this:
g++ -g -O2 -o chap1ex1 chap1ex1.o ../../libgasandbox/libgasandbox.a -lGL -lGLU -lglut
Order of arguments does matter for static linking, as described in this answer: things that depend on a library must come before that library. libgasandbox evidently depends on GLU, so putting it earlier should solve that error.
You might also need to move -lGL to the very end, if GLU or glut depend on it (I'm not sure whether they do).

Symbol(s) not found for architecture x86_64 (OpenGL with xcode)

I am very new to using OpenGL. The program I am trying to run is provided by my professor so I have not actually written any of it, I am having problems getting the program to run. The program is suppose to just make a white square on a black screen. I am using mac Sierra 10.12.2. Also I have already changed the deployment target to 10.8 because of the errors from compiling in anything later than that. Now when I try to build and run in xcode I get 2 errors.
These are the errors im getting,
Undefined symbols for architecture x86_64:
"exit(int)", referenced from:
myKeyboard(unsigned char, int, int) in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Now here is the code exactly as I am trying to compile it.
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
const int screenHeight = 480; // window height is 480
const int screenWidth = 640 ; //window width is 640
// <<<<<<<<<<<<<<<<<<<<< Prototypes >>>>>>>>>>>>>>>>>>
void exit(int) ;
// <<<<<<<<<<<<<<<<<<<<<<< myInit >>>>>>>>>>>>>>>>>>>
void myInit(void)
{
glClearColor(1.0,1.0,1.0,0.0); // set white background color
glColor3f(0.0f, 0.0f, 0.0f); // set the drawing color
glPointSize(4.0); // a ?dot? is 4 by 4 pixels
glLineWidth(4.0); // a ?dot? is 4 by 4 pixels
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
}
// <<<<<<<<<<<<<<<<<<<<<<<< myDisplay >>>>>>>>>>>>>>>>>
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT); // clear the screen
glBegin(GL_POINTS);
// glBegin(GL_LINE_STRIP) ;
// glBegin(GL_LINE_LOOP) ;
// glBegin(GL_POLYGON);
glVertex2i(289, 190); // Dubhe
glVertex2i(320, 128) ; // Merak
glVertex2i(239, 67) ; // Phecda
glVertex2i(194, 101) ; // Megrez
glVertex2i(129, 83) ; // Alioth
glVertex2i(75, 73) ; // Mizar
glVertex2i(74, 74) ; // Alcor
glEnd();
glFlush(); // send all output to display
}
// <<<<<<<<<<<<<<<<<<<<<<<< myKeyboard >>>>>>>>>>>>>>
void myKeyboard(unsigned char theKey, int mouseX, int mouseY)
{
switch(theKey)
{
case 'Q':
case 'q':
exit(-1); //terminate the program
default:
break; // do nothing
}
}
// <<<<<<<<<<<<<<<<<<<<<<<< main >>>>>>>>>>>>>>>>>>>>>>
int main(int argc, char** argv)
{
glutInit(&argc, argv); // initialize the toolkit
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); // set display mode
glutInitWindowSize(640, 480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("Big Deep - Type Q or q to quit") ; // open the screen window
glutDisplayFunc(myDisplay); // register redraw function
glutKeyboardFunc(myKeyboard); // register the keyboard action function
myInit();
glutMainLoop(); // go into a perpetual loop
}
Any help would be greatly appreciated!
You need to add the following near the top of your source file:
#include <stdlib.h>
and remove this line:
void exit(int) ;
First, you should always use the proper system headers to get the declarations of system library functions. This is especially true on macOS where the declaration can have important attributes which affect how the function is linked.
However, the lack of such attributes is not really what tripped you up in this case. The issue here is that you're building a C++ program. In C++, a function's argument types are part of its symbol name. You can see this in the error message you've quoted. But the exit() function is part of the C standard library. It's not natively a C++ interface. Its symbol name is _exit, with no indication of its argument count or types.
Your code has incorporated references to a symbol that translates to exit(int) while the actual symbol in the system library is just _exit. They don't match, so you get a symbol-not-found linker error.
The stdlib.h header takes special care to wrap its function declarations in extern "C" { ... } when it's included for a C++ translation unit. So, including that header to get the declaration tells the C++ compiler not to use a C++-style symbol name but to instead just use the C-style symbol name.
You could also "solve" the issue by putting extern "C" on the declaration of exit() in your own code, but that's the wrong approach. Just include the proper header.

c++ program and scope variables [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I compiled this c++ program with dev-c++ and give "was not declared in this scope" for all variables.
#include <cstdlib> // standard definitions
#include <iostream> // C++ I/O
#include <cstdio> // C I/O (for sprintf)
#include <cmath> // standard definitions
#include <GL/glut.h> // GLUT
#include <GL/glu.h> // GLU
#include <GL/gl.h> // OpenGL
using namespace std; // make std accessible
//-----------------------------------------------------------------------
// Global data
//-----------------------------------------------------------------------
GLint TIMER_DELAY = 10000; // timer delay (10 seconds)
GLfloat RED_RGB[] = {1.0, 0.0, 0.0}; // drawing colors
GLfloat BLUE_RGB[] = {0.0, 0.0, 1.0};
//-----------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------
static bool isReversed = false; // draw reversed colors?
//-----------------------------------------------------------------------
// Callbacks
// The global variable "isReversed" describes the drawing state.
// When false, a blue rectangle is drawn on top of red diamond.
// When true the colors are reversed. The "isReversed" variable is
// complemented whenever the left mouse button is clicked or the
// timer goes off (every 10 seconds).
//-----------------------------------------------------------------------
void myReshape(int w, int h) {
cout << "MyReshape called width=" << w << " height=" << h << endl;
glViewport (0, 0, w, h); // update the viewport
glMatrixMode(GL_PROJECTION); // update projection
glLoadIdentity();
gluOrtho2D(0.0, 1.0, 0.0, 1.0); // map unit square to viewport
glMatrixMode(GL_MODELVIEW);
glutPostRedisplay(); // request redisplay
}
// draw diamond and rectangle
void drawObjects(GLfloat* diamColor, GLfloat* rectColor) {
glColor3fv(diamColor); // set diamond color
glBegin(GL_POLYGON); // draw the diamond
glVertex2f(0.90, 0.50);
glVertex2f(0.50, 0.90);
glVertex2f(0.10, 0.50);
glVertex2f(0.50, 0.10);
glEnd();
glColor3fv(rectColor); // set rectangle color
glRectf(0.25, 0.25, 0.75, 0.75); // draw the rectangle
}
void myDisplay(void) { // display callback
cout << "MyDisplay called" << endl;
glClearColor(0.5, 0.5, 0.5, 1.0); // background is gray
glClear(GL_COLOR_BUFFER_BIT); // clear the window
if (isReversed) // draw the objects
drawObjects(BLUE_RGB, RED_RGB);
else
drawObjects(RED_RGB, BLUE_RGB);
glutSwapBuffers(); // swap buffers
}
void myTimer(int id) { // timer callback
cout << "Timer just went off. Reversing colors." << endl;
isReversed = !isReversed; // reverse drawing colors
glutPostRedisplay(); // request redraw
glutTimerFunc(TIMER_DELAY, myTimer, 0); // reset timer for 10 seconds
}
void myMouse(int b, int s, int x, int y) { // mouse click callback
if (s == GLUT_DOWN) {
cout << "Mouse click detected at coordinates x="
<< x << " and y=" << y << endl;
if (b == GLUT_LEFT_BUTTON) {
isReversed = !isReversed;
cout << "Left mouse click. Reversing colors." << endl;
glutPostRedisplay();
}
}
}
// keyboard callback
void myKeyboard(unsigned char c, int x, int y) {
switch (c) { // c is the key that is hit
case 'q': // 'q' means quit
exit(0);
break;
default:
cout << "Hit q to quit. All other characters ignored" << endl;
break;
}
}
//-----------------------------------------------------------------------
// Main program
// This does all the set up for the program. It creates the game
// and then passes control to glut.
//-----------------------------------------------------------------------
int main(int argc, char** argv)
{
cout <<
"Colors swap every 10 seconds.\n"
"Click left mouse button to swap colors.\n" <<
"Try resizing and covering/uncovering the window.\n" <<
"Hit q to quit." << endl;
glutInit(&argc, argv); // OpenGL initializations
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);// double buffering and RGB
glutInitWindowSize(400, 400); // create a 400x400 window
glutInitWindowPosition(0, 0); // ...in the upper left
glutCreateWindow(argv[0]); // create the window
glutDisplayFunc(myDisplay); // setup callbacks
glutReshapeFunc(myReshape);
glutMouseFunc(myMouse);
glutKeyboardFunc(myKeyboard);
glutTimerFunc(TIMER_DELAY, myTimer, 0);
glutMainLoop(); // start it running
return 0; // ANSI C expects this
}
Where is the problem?
[Error] 'glutPostRedisplay' was not declared in this scope
[Error] 'glutSwapBuffers' was not declared in this scope
[Error] 'glutPostRedisplay' was not declared in this scope
[Error] 'glutTimerFunc' was not declared in this scope
[Error] 'GLUT_DOWN' was not declared in this scope
[Error] 'GLUT_LEFT_BUTTON' was not declared in this scope
[Error] 'glutPostRedisplay' was not declared in this scope
etc.
From the GLUT docs here:
The header files for GLUT should be included in GLUT programs with the following include directive (which you have):
#include <GL/glut.h>
Because a very large window system software vendor (who will remain nameless) has an apparent inability to appreciate that OpenGL's API is independent of their window system API, portable ANSI C GLUT programs should not directly include <GL/gl.h> or <GL/glu.h>. Instead, ANSI C GLUT programs should rely on <GL/glut.h> to include the necessary OpenGL and GLU related header files.
If you are not on windows, this may be causing an issue.
It does look like this file is not being included correctly since even the symbolic constants (e.g. for GLUT_DOWN) are not being resolved.
You should look for the header files that declare these functions and variables and include them in this source file.
A good place to start would be this GL directory you seem to be including glut.h from, assuming it exists.
Check building without calling functions in main(). Then try one by one. I think the error is coming from one of your include files.
Are there any classes defined in those files. Check there header files are ok or not. Check for the existence of header files in specified paths.
Then check the namespaces. If you defined a class with a namespace, don't forget to use using namespace namespace_name or specify full qualified name for variables.