I get this error when trying to make the executable, the code compiles correctly and yet when I hit the make command I get this error message:
gcc -c helloworld.c
lewis#lewis-desktop ~/Desktop/Dev/gl $ make
gcc -o hello-gl helloworld.o -L/usr/X11R6/lib -lGL -lglut -lGLEW -lm
helloworld.o: In function `Initialize':
helloworld.c:(.text+0x55): undefined reference to `GlewInit'
collect2: ld returned 1 exit status
make: *** [helloworld] Error 1
I'm running Linux Mint 13 and I think it's something to do with my makefile, I don't know too much about them so I hacked one together and found some code online:
GL_INCLUDE = /usr/X11R6/include
GL_LIB = /usr/X11R6/lib
GL_GLEW = /user/include
helloworld: helloworld.o
gcc -o hello-gl $^ -L$(GL_LIB) -lGL -lglut -lGLEW -lm
.c.o:
gcc -c -o $# $< -I$(GL_INCLUDE)
clean:
rm -f hello-gl hello-gl-dummy hello-gl.o util.o hello-gl-dummy.o
My Code:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#define WINDOW_TITLE_PREFIX "Hello, World!"
int CurrentWidth = 600,
CurrentHeight = 400,
WindowHandle = 0;
void Initialize(int, char*[]);
void InitWindow(int, char*[]);
void ResizeFunction(int, int);
void RenderFunction(void);
int main(int argc, char* argv[])
{
Initialize(argc, argv);
glutMainLoop();
exit(EXIT_SUCCESS);
return 0;
}
void Initialize(int argc, char* argv[])
{
GLenum GlewInitResult;
InitWindow(argc, argv);
GlewInitResult = GlewInit();
if (GLEW_OK != GlewInitResult) {
fprintf(stderr, "ERROR: %s\n", glewGetErrorString(GlewInitResult));
exit(EXIT_FAILURE);
}
fprintf(
stdout,
"INFO: OpenGL Version: %s\n",
glGetString(GL_VERSION)
);
glClearColor(0.2f, 1.0f, 0.8f, 0.3f);
}
void InitWindow(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitContextVersion(4, 0);
glutInitContextFlags(GLUT_FORWARD_COMPATIBLE);
glutInitContextProfile(GLUT_CORE_PROFILE);
glutSetOption(
GLUT_ACTION_ON_WINDOW_CLOSE,
GLUT_ACTION_GLUTMAINLOOP_RETURNS
);
glutInitWindowSize(CurrentWidth, CurrentHeight);
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
char *states[] = {"Hello", "My", "Name", "Is", "Lewis"};
WindowHandle = glutCreateWindow(WINDOW_TITLE_PREFIX);
if(WindowHandle < 1) {
fprintf(
stderr,
"KERN_ERROR: Could not create a new rendering window.\n"
);
exit(EXIT_FAILURE);
}
glutReshapeFunc(ResizeFunction);
glutDisplayFunc(RenderFunction);
}
void ResizeFunction(int Width, int Height)
{
/*captures the resize data from the OS and assigns it to the global
variable CURRENT_WIDTH & CURRENT_HEIGHT */
CurrentWidth = Width;
CurrentHeight = Height;
glViewport(0, 0, CurrentWidth, CurrentHeight);
}
void RenderFunction(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/*the next line takes the data from the back-buffer to the screen */
glutSwapBuffers();
glutPostRedisplay();
}
The names for the GLEW functions should start from 'glew', not 'Glew'.
So it is
GlewInitResult = glewInit();
C is case-sensitive and all the OpenGL-related libs usually start the names of the functions with lowercase letters.
Related
When I compile my code in the ubuntu terminal, it compiles perfectly, but when I execute the command in the VSCode integrated terminal, it gives me an error:
main.c:1:10: fatal error: no such file or directory
here's the command I use:
$ gcc main.c $(sdl2-config --cflags --libs) -o prog
and here is my code:
#include <SDL.h>
#include <stdio.h>
int main(int argc, char **argv) {
SDL_Window *window = NULL;
if(SDL_Init(SDL_INIT_VIDEO) != 0) {
SDL_Log("ERROR: SDL Initialization > %s\n", SDL_GetError());
exit(EXIT_FAILURE);
}
// program execution
window = SDL_CreateWindow("SDL2 Window", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, 0);
if(window == NULL) {
SDL_Log("ERROR: SDL Initialization > %s\n", SDL_GetError());
exit(EXIT_FAILURE)
}
SDl_Quit();
return EXIT_SUCCESS;
}
I'm trying to call D-Bus method, but don't understand how to add needed args.
Method name: CreateSession (String destination, Dict of {String, Variant} args) ↦ (Object Path session)
Bus Name: org.bluez.obex
Object Path: /org/bluez/obex
Interface: org.bluez.obex.Client1
I successfully can call this method in D-Feet app with this arguments:
"D0:9C:7A:A1:A4:63",{'Target':GLib.Variant('s','OPP')}
But how make the same using only dbus.h?
Here's my code:
// Do before compile sudo apt-get install -y libdbus-1-dev
// gcc -o test -Wall test.c `pkg-config --cflags dbus-1` `pkg-config --libs dbus-1`
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dbus/dbus.h>
int main() {
DBusConnection *sesBusCon;
DBusError error;
DBusMessage *call;
DBusMessage *reply;
dbus_error_init(&error);
if (dbus_error_is_set(&error)) {
fprintf(stderr, "%s", error.message);
return 1;
}
sesBusCon = dbus_bus_get(DBUS_BUS_SESSION, &error);
if (dbus_error_is_set(&error)) {
fprintf(stderr, "%s", error.message);
return 1;
}
call = dbus_message_new_method_call("org.bluez.obex", "/org/bluez/obex", "org.bluez.obex.Client1", "CreateSession");
reply = dbus_connection_send_with_reply_and_block (sesBusCon, call, 100000, &error);
if (dbus_error_is_set(&error)) {
fprintf(stderr, "%s", error.message);
return 1;
}
return 0;
}
Maybe it helps someone:
// Do before compile sudo apt-get install -y libdbus-1-dev
// gcc -o test -Wall test.c `pkg-config --cflags dbus-1` `pkg-config --libs dbus-1`
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dbus/dbus.h>
int main() {
DBusConnection *sesBusCon;
DBusError error;
DBusMessage *call;
DBusMessage *reply;
DBusMessageIter iterInit, iterDict, iterEntry, iterValue;
dbus_error_init(&error);
if (dbus_error_is_set(&error)) {
fprintf(stderr, "%s", error.message);
return 1;
}
sesBusCon = dbus_bus_get(DBUS_BUS_SESSION, &error);
if (dbus_error_is_set(&error)) {
fprintf(stderr, "%s", error.message);
return 1;
}
call = dbus_message_new_method_call("org.bluez.obex", "/org/bluez/obex", "org.bluez.obex.Client1", "CreateSession");
char *destination = "D0:9C:7A:A1:A4:63";
dbus_message_append_args(call, DBUS_TYPE_STRING, &destination, DBUS_TYPE_INVALID);
dbus_message_iter_init_append(call, &iterInit);
dbus_message_iter_open_container(&iterInit, DBUS_TYPE_ARRAY,
DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &iterDict);
dbus_message_iter_open_container(&iterDict, DBUS_TYPE_DICT_ENTRY, NULL, &iterEntry);
char *key = "Target";
dbus_message_iter_append_basic(&iterEntry, DBUS_TYPE_STRING, &key);
dbus_message_iter_open_container(&iterEntry, DBUS_TYPE_VARIANT, DBUS_TYPE_STRING_AS_STRING, &iterValue);
void *val = "OPP";
dbus_message_iter_append_basic(&iterValue, DBUS_TYPE_STRING, &val);
dbus_message_iter_close_container(&iterEntry, &iterValue);
dbus_message_iter_close_container(&iterDict, &iterEntry);
dbus_message_iter_close_container(&iterInit, &iterDict);
DBusPendingCall* replyPending;
DBusMessage* replyMessage;
DBusMessageIter replyIter;
dbus_connection_send_with_reply(sesBusCon, call, &replyPending, -1);
dbus_pending_call_block(replyPending);
if (dbus_pending_call_get_completed (replyPending))
{
replyMessage = dbus_pending_call_steal_reply(replyPending);
dbus_message_iter_init(replyMessage, &replyIter);
char *objectPath;
dbus_message_iter_get_basic(&replyIter, &objectPath);
printf("object path %s \n",objectPath);
}
return 0;
}
All I want is just a simple dialog to select a file for processing.
I didn't use C lang for a while, and I can't find a good working example.
code:
#include <gtk/gtk.h>
#include <stdio.h>
int main(int argc, char const *argv[]) {
GtkFileChooserNative *native;
native = gtk_file_chooser_native_new ("Open File", NULL, GTK_FILE_CHOOSER_ACTION_OPEN, NULL, NULL);
return 0;
}
I compile it with this command:
gcc `pkg-config gtk+-3.0 --cflags` `pkg-config gtk+-3.0 --libs` -o out dialog.c
I am having segmentation fault on gtk_file_chooser_native_new ()
Maybe strace will help:
http://pastebin.com/TdC0A2J3
You need to call gtk_init (before any other GTK function), or have your own application class and call g_application_run. And your main should be int main(int argc, char**argv) as usual.
The following program does not segfault (on Linux/Debian/Sid, GTK is 3.22.7)
#include <gtk/gtk.h>
#include <stdio.h>
int main (int argc, char **argv) {
GtkFileChooserNative *native = NULL;
gtk_init (&argc, &argv);
native = gtk_file_chooser_native_new ("Open File", NULL,
GTK_FILE_CHOOSER_ACTION_OPEN, NULL, NULL);
guint res = gtk_native_dialog_run (GTK_NATIVE_DIALOG (native));
if (res == GTK_RESPONSE_ACCEPT) {
char *filename;
GtkFileChooser *chooser = GTK_FILE_CHOOSER (native);
filename = gtk_file_chooser_get_filename (chooser);
printf ("should open %s\n", filename);
g_free (filename);
}
/// in a real application perhaps you want: gtk_main ();
return 0;
}
and does show a dialog. Compile that using
gcc -Wall -g $(pkg-config gtk+-3.0 --cflags) \
$(pkg-config gtk+-3.0 --libs) \
-o out dialog.c
and use the gdb debugger when debugging.
I am new to SDL_image and I am trying to use it in a C file to load a BMP image.
To that end, I have written the following code:
#include "SDL/SDL.h"
#include "SDL_image.h"
SDL_RWops *rwop;
rwop = SDL_RWFromFile("sample.bmp", "rb");
However, for some reason, although rwop after those lines are executed is not NULL anymore, IMG_isBMP(rwop) is 0.
Any idea what could be wrong?
Perhaps better example. This (might) yield more information and perhaps if BMP is supported:
https://www.libsdl.org/projects/SDL_image/docs/SDL_image_32.html
You could also try using IMG_LoadBMP_RW as per example here:
https://www.libsdl.org/projects/SDL_image/docs/SDL_image_16.html#SEC16
#include <stdio.h>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
int main(int argc, char *argv[])
{
const char *fn = "sample.bmp";
SDL_Surface *surf;
if (argc > 1)
fn = argv[1];
if ((surf = SDL_LoadBMP(fn)) == NULL) {
printf("SDL_loadBMP failed: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}
printf("%s is bmp\n", fn);
SDL_FreeSurface(surf);
SDL_Quit();
return 0;
}
Old answer:
Tested and validated:
#include <stdio.h>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
int main(int argc, char *argv[])
{
const char *fn = "sample.bmp";
int v;
SDL_RWops *rwop;
if (argc > 1)
fn = argv[1];
if ((rwop = SDL_RWFromFile(fn, "rb")) == NULL) {
printf("SDL_RWFromFile failed: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}
v = IMG_isBMP(rwop);
printf("%s is bmp = %d\n", fn, v);
SDL_FreeRW(rwop);
SDL_Quit();
return 0;
}
Compiled with:
gcc -Wall -Wextra -pedantic -o sdl sdl.c `sdl-config --libs` -lSDL_image
Yield for BMP images, e.g.:
$ ./sdltest lena.bmp
lena.bmp is bmp = 1
I have to compile two independent processes-sendfdsock.c and recvfdsock.c using make file. Both the files have there own main function. This means they are independent and I have to compile them as two different binaries. This is my make file:
compileAll:sendfdsock recvfdsock
sendfdsock:sendfdsock.o
gcc -o sendfdsock sendfdsock.o
sendfdsock.o:sendfdsock.c accessories.h
gcc -c sendfdsock.c
recvfdsock.o:recvfdsock.c accessories.h
gcc -c recvfdsock.c
recvfdsock:recvfdsock.o
gcc -o recvfdsock recvfdsock.o
Here I have made a compileAll target which compiles both the files.
Both files need to use accessories.h. As mention in GNU Make Doc - A simple Make file. I wrote this make file.
accessories.h :
#include <malloc.h>
#include <time.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <error.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <sys/un.h>
#include <stropts.h>
#define PORT "4444" //port we are listening on
int sendall(int fd, char *buf, int *len);
int recvall(int fd, char *buf, int *len);
void logp(int typ, char* msg);
void errorp(char *where, int boolean, int errn,char *what);
accessories.c :
#include "accessories.h"
void logp(int typ, char* msg) // typ --> type(category) of message [1-Normal Log, 2-Warning(any unexpected thing happened), 3-Error, 4-Debugging Log ]
{
int fd;
time_t now;
ssize_t wlength=0;
char * dat;
char * str;
int size = 45+strlen(msg);//14+24+5+sizeof msg+1
str= (char *) malloc(size);
time(&now);//system time in seconds
dat = ctime(&now); // converting seconds to date-time format
dat = strtok(dat,"\n");
//Appending type of log
switch(typ)
{
case 1:
strcpy(str,"__LOG__ | ");
strcat(str,dat);
break;
case 2:
strcpy(str,"__WARN__ | ");
strcat(str,dat);
break;
case 3:
strcpy(str,"__ERR__ | ");
strcat(str,dat);
break;
case 4:
strcpy(str,"__DEBUG__ | ");
strcat(str,dat);
break;
default:
strcpy(str,"__UNDEF__ | ");
strcat(str,dat);
break;
}
strcat(str," | ");
strcat(str,msg);//appending message
strcat(str,"\n");
fd = open("log", O_WRONLY | O_CREAT | O_APPEND, 0644); // should be opened somewhere else
if (fd == -1)
printf("Could not open log - %s\n",strerror(errno));
else
{//need to add lock to the file and printing error message
while ( wlength < strlen(str) )
{
wlength = write(fd, str,strlen(str));
if (wlength == -1)
{
printf("Error : writing log\n");
break;
}
}
}
}
int sendall(int fd, char *buf, int *len)
{
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
int n;
while(total < *len) {
n = send(fd, buf+total, bytesleft, 0);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
*len = total; // return number actually sent here
return n==-1?-1:0; // return -1 on failure, 0 on success
}
int recvall(int fd, char *buf, int *len)
{
int total = 0; // how many bytes we've sent
int bytesleft = *len; // how many we have left to send
int n;
while(total < *len) {
n = recv(fd, buf+total, bytesleft, 0);
if (n == -1) { break; }
total += n;
bytesleft -= n;
}
*len = total; // return number actually sent here
return n==-1?-1:0; // return -1 on failure, 0 on success
}
void errorp(char *where, int boolean, int errn,char *what)
{
char errmsg[21+strlen(where)];
strcpy(errmsg,"Where - ");
strcat(errmsg,where);
strcat(errmsg," | Error - ");
if(boolean == 1)//we got error number
{
strcat(errmsg,strerror(errn));
//fprintf(stderr,"ERROR - In %s and error is %s\n",where ,strerror(errn));
logp(3,errmsg);
}
else if(boolean == 0)//we got a message
{
strcat(errmsg,what);
//fprintf(stderr,"ERROR - In %s and error is %s\n",where ,what);
logp(3,errmsg);
}
else//we got nothing
{
strcat(errmsg,"No Message");
//fprintf(stderr,"ERROR - In %s\n",where);
logp(3,errmsg);
}
}
Initially everything work fine but when I trid to use any function which is defined in accessories.c compilation give me error.
For example I use the log function in sendfdsock.c :
#include "accessories.h"
#define CONTROLLEN CMSG_LEN(sizeof(int))
static struct cmsghdr *cmptr = NULL; /* malloc'ed first time */
int send_err(int fd, int errcode, const char *msg);
int send_fd(int fd, int fd_to_send);
int main(int argc, char const *argv[])
{
logp(1,"started"); //This function is defined in accessories.c
int fd_to_send;
if((fd_to_send = open("vi",O_RDONLY)) < 0)
printf("vi open failed");
struct sockaddr_un address;
int socket_fd, nbytes;
char buffer[256];
........
Output of the compilation is:
abhi#abhi-me:~/bridge/server$ make compileAll
gcc -c sendfdsock.c
sendfdsock.c: In function ‘send_fd’:
sendfdsock.c:111:9: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘ssize_t’ [-Wformat]
sendfdsock.c:114:5: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘ssize_t’ [-Wformat]
gcc -o sendfdsock sendfdsock.o
sendfdsock.o: In function `main':
sendfdsock.c:(.text+0x32): undefined reference to `logp'
collect2: ld returned 1 exit status
make: *** [sendfdsock] Error 1
abhi#abhi-me:~/bridge/server$
Why undefined reference to logp error?
Why I don't write accessories.o in final linking:
But as this example is given in GNU Make Doc:
In this example, all the C files include ‘defs.h’, but
only those defining editing comminclude ‘command.h’, and only
low level files that change the editor buffer include 'buffer.h':
edit : main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
cc -o edit main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
main.o : main.c defs.h
cc -c main.c
kbd.o : kbd.c defs.h command.h
cc -c kbd.c
command.o : command.c defs.h command.h
cc -c command.c
display.o : display.c defs.h buffer.h
cc -c display.c
insert.o : insert.c defs.h buffer.h
cc -c insert.c
search.o : search.c defs.h buffer.h
cc -c search.c
files.o : files.c defs.h buffer.h command.h
cc -c files.c
utils.o : utils.c defs.h
cc -c utils.c
clean :
rm edit main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
Here while linking all the files in edit they don't write defs.o or buffer.o. Means while linking they are not including object files of header files. Also they have not written any target like: defs.o or buffer.o
Why?
You just missed accessories.o in both linking targets. Something like this:
accessories.o: accessories.c
sendfdsock: sendfdsock.o accessories.o
$(CC) -o $# $(CFLAGS) $(LDFLAGS) $+
Also, consider using the built-in rules, just modify their parameters, if needed. See make -p for the full list (and makes infopage)
You misunderstand the relationship between source files, header files and object files.
Suppose I have the following four files:
//foo.h
#define PI 3.1
//bar.h
void func();
//bar.c
#include "foo.h"
#include "bar.h"
void func()
{
...
}
//baz.c
#include "foo.h"
#include "bar.h"
int main()
{
func();
}
(I left out the header guards, I presume you know about those.) I must use the compiler to produce an object file from each source file: bar.c -> bar.o and baz.c -> baz.o. I don't have to make object files from the headers foo.h and bar.h, those will simply be #included by any source file that needs them. Then I link the object files together to form an executable:
baz: bar.o baz.o
gcc -o baz bar.o baz.o
bar.o: bar.c foo.h bar.h
gcc -c bar.c
baz.o: baz.c foo.h bar.h
gcc -c baz.c
If I neglect to link bar.o into the executable, I'll get a linker error when the linker gets to the place where baz calls func() and the linker doesn't know what to put there (because it lacks the definition of func() in bar.o):
baz.o: In function `main':
baz.c:(.text+0x32): undefined reference to `func()'
So the GNU Make doc is correct, and as Alex said, your rule should have:
sendfdsock:sendfdsock.o accessories.o
...
accessories.o: accessories.c accessories.h
...
(Incidentally, once you get this makefile working, we can show you how to make it more concise.)