Trying to compile following code in C (I'm not very good with it) and getting Address boundary error. It seems like a variable is uninitialized.
all:
gcc -Wall -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include test.c `pkg-config --cflags dbus-1` `pkg-config --libs dbus-1 gio-unix-2.0`

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gio/gio.h>
#include <glib-2.0/glib.h>
int main (){
GIOStream stream;
GDBusConnectionFlags flags = G_DBUS_CONNECTION_FLAGS_NONE;
GError *gerr = NULL;
GDBusConnection * gcon = g_dbus_connection_new_sync(&stream,
NULL,
flags,
NULL,
NULL,
&gerr);
return 0;
}
Here is the documentation for GDBusConnection and GIOStream.
I can't understand what is wrong with the code. Can you explain?
After few more time I figured out that following works:
GInputStream * ginput = g_memory_input_stream_new();
GOutputStream * goutput = g_memory_output_stream_new (NULL, 0, realloc, free);
GIOStream * stream = g_simple_io_stream_new(ginput, goutput);
GDBusConnectionFlags flags = G_DBUS_CONNECTION_FLAGS_NONE;
GError* gerr = NULL;
GDBusConnection * gcon = g_dbus_connection_new_sync(stream,
NULL,
flags,
NULL,
NULL,
&gerr);
if (gerr){
printf(gerr->message, "%s");
}
Related
I am trying to create an instance and validate that the code can create that instance.
However, For some reason code compiles and fails to create the instance. I do not know what I am doing wrong. Everything before creating instance works. but When I try to validate instance creation it fails. I am using SDL2 to create the window.
This is my cmakelist file:
cmake_minimum_required(VERSION 3.16)
#COMPIER
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_C_COMPILER "gcc")
set(CMAKE_C_STANDARD 17)
set(CMAKE_C_STANDARD_REQUIRED ON)
#FLAGS
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -O0 -ggdb3")
set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra")
#PROJECT
project(Vulkan_test LANGUAGES C)
enable_language(C)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
#Find packages installed in your system.
include(FindPkgConfig)
pkg_search_module(SDL2 REQUIRED sdl2)
pkg_search_module(Vulkan REQUIRED vulkan)
#Include global directories
include_directories(
${SDL2_INCLUDE_DIRS}
${Vulkan_INCLUDE_DIRS}
)
#Executable Specific
add_executable(VULKAN_TEST
${CMAKE_CURRENT_SOURCE_DIR}/main.c
)
#Compile options
target_compile_options(VULKAN_TEST PUBLIC -O0 -ggdb3 -std=c2x -Wall -Wextra -Wmissing-prototypes -Wwrite-strings -Wpedantic)
#Libraries to link
target_link_libraries(
VULKAN_TEST
${SDL2_LIBRARIES}
${Vulkan_LIBRARIES}
)
This is the is the main.h file that I have:
#pragma once
/* Required Standard Headers */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
/* SDL2 */
#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>
/* Vulkan */
#include <vulkan/vulkan.h>
#define rt_assert(expr, ...) ((void) sizeof ((expr) ? 1 : 0), __extension__ ({ \
if (!(expr)) { \
fprintf(stderr,"At function [%s] in file [%s:%d], assert failed: [(%s)].\n", __func__, __FILE__, __LINE__, (#expr)); \
__VA_ARGS__; \
exit(EXIT_FAILURE); \
} \
}))
typedef struct _App {
SDL_Window *window;
int window_height;
int window_width;
const char* window_name;
SDL_Event sdl_event;
bool quit;
VkInstance inst;
uint32_t sdlExtCount;
const char** extNames;
} App;
/* Function Prototype */
void init_window(App *);
void init_vulkan(App *);
void main_loop(App *);
void cleanup(App *);
/* sub vulkan functions */
void init_vk_instance(App *);
This file my main.c
#include "main.h"
#define SDL_MAIN_HANDLED
#define App_init(X) App (X) = { \
.window = NULL, .window_height = 600, .window_width = 800, \
.window_name = "Vulkan Test", .quit = false, \
.inst = VK_NULL_HANDLE \
}
VkApplicationInfo appInfo = {0};
VkInstanceCreateInfo instInfo = {0};
void init_vk_instance(App *App) {
/* Vulkan VkApplicationInfo */
appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
appInfo.pApplicationName = App->window_name;
appInfo.applicationVersion = VK_MAKE_API_VERSION(0, 1, 0, 0);
appInfo.pEngineName = App->window_name;
appInfo.engineVersion = VK_MAKE_API_VERSION(0, 1, 0, 0);
/* This is version I have installed from my linux package manager */
appInfo.apiVersion = VK_MAKE_API_VERSION(0,1,3,231);
appInfo.pNext = NULL;
/* Vulkan Instance info - VkInstanceCreateInfo */
instInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instInfo.pApplicationInfo = &appInfo;
instInfo.enabledLayerCount = 0;
SDL_Vulkan_GetInstanceExtensions(App->window,&App->sdlExtCount,NULL);
App->extNames = malloc(App->sdlExtCount * sizeof(const char*));
SDL_Vulkan_GetInstanceExtensions(App->window,&App->sdlExtCount,App->extNames);
instInfo.enabledExtensionCount = App->sdlExtCount;
instInfo.ppEnabledExtensionNames = App->extNames;
for(uint32_t i = 0; i < App->sdlExtCount; i++) {
printf("%u : %s\n",i,App->extNames[i]);
}
rt_assert( (vkCreateInstance(&instInfo, NULL, &App->inst) == VK_SUCCESS), printf("Instance creation failed\n"), cleanup(App));
}
void init_vulkan(App *App) {
init_vk_instance(App);
}
void init_window(App *App) {
App->window = SDL_CreateWindow( App->window_name,
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
App->window_width, App->window_height, SDL_WINDOW_SHOWN | SDL_WINDOW_VULKAN |
SDL_WINDOW_RESIZABLE);
}
void cleanup(App *App) {
free(App->extNames);
SDL_DestroyWindow(App->window);
SDL_Quit();
}
void main_loop(App *App) {
while(!App->quit) {
while (SDL_PollEvent(&App->sdl_event)) {
if( App->sdl_event.type == SDL_QUIT ) App->quit = true;
}
}
}
int main ( void ) {
printf("Vulkan-Engine\n");
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
App_init(test);
init_window(&test);
init_vulkan(&test);
main_loop(&test);
vkDestroyInstance(test.inst, NULL);
cleanup(&test);
return EXIT_SUCCESS;
}
This the output I get after running my program:
Vulkan-Engine
0 : VK_KHR_surface
1 : VK_KHR_xlib_surface
At function [init_vk_instance] in file [/home/Codes/C/Vulkan/main.c:35], assert failed: [((vkCreateInstance(&instInfo, NULL, &App->inst) == VK_SUCCESS))].
Instance creation failed
CMake output during compilation:
-- The C compiler identification is GNU 12.2.0
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: /usr/bin/gcc - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Found PkgConfig: /usr/bin/pkg-config (found version "0.29.2")
-- Checking for one of the modules 'sdl2'
-- Checking for one of the modules 'vulkan'
-- Configuring done
-- Generating done
-- Build files have been written to: /home/Codes/C/Vulkan/build
[ 50%] Building C object CMakeFiles/VULKAN_TEST.dir/main.c.o
[100%] Linking C executable /home/Codes/C/Vulkan/VULKAN_TEST
[100%] Built target VULKAN_TEST
These are the vulkan related package I have installed on my system through package manager:
As you see from the image the vulkan api version is 1.3.231.1_1. Am I using the VK_MAKE_API_VERSION(0,1,3,231) properly?
I think you are missing KHR macro
For example I am using windows 10 and MSYS2
This is what I did
#define VK_USE_PLATFORM_WIN32_KHR
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#include <SDL2/SDL_vulkan.h>
#include <vulkan/vulkan.h>
#include <vulkan/vulkan_core.h>
int main(int argc, char** argv)
{
if (0 != SDL_Init(SDL_INIT_EVERYTHING))
{
printf("failed to initialize SDL2 with everything\n");
}
SDL_Window* window = SDL_CreateWindow("test", 10, 10, 640, 480, SDL_WINDOW_SHOWN | SDL_WINDOW_VULKAN);
if (NULL == window)
{
printf("failed to create window\n");
}
VkApplicationInfo app_info = { 0 };
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.apiVersion = VK_API_VERSION_1_3;
app_info.pApplicationName = "test-app";
app_info.applicationVersion = VK_MAKE_API_VERSION(1, 0, 0, 0);
app_info.pEngineName = "test-engine";
app_info.engineVersion = VK_MAKE_API_VERSION(1, 0, 0, 0);
VkInstanceCreateInfo instance_info = { 0 };
instance_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instance_info.pApplicationInfo = &app_info;
instance_info.enabledLayerCount = 0;
instance_info.ppEnabledLayerNames = NULL;
unsigned int count = 0;
SDL_Vulkan_GetInstanceExtensions(window, &count, NULL);
const char** extensions = malloc(sizeof(char*) * count);
SDL_Vulkan_GetInstanceExtensions(window, &count, extensions);
for (unsigned int i = 0; i < count; i ++)
{
printf("%u: %s\n", i, extensions[i]);
}
instance_info.enabledExtensionCount = count;
instance_info.ppEnabledExtensionNames = extensions;
VkInstance instance = VK_NULL_HANDLE;
if (0 > vkCreateInstance(&instance_info, NULL, &instance))
{
printf("failed to create instance\n");
}
VkSurfaceKHR surface = VK_NULL_HANDLE;
if (SDL_FALSE == SDL_Vulkan_CreateSurface(window, instance, &surface))
{
printf("failed to create surface, SDL Error: %s", SDL_GetError());
}
return 0;
}
For me it is working fine, so my observation is you need to find a way for defining similar macro like #define VK_USE_PLATFORM_WIN32_KHR
Below are the list extensions assumed in vulkan.h
VK_USE_PLATFORM_ANDROID_KHR
VK_USE_PLATFORM_FUCHSIA
VK_USE_PLATFORM_IOS_MVK
VK_USE_PLATFORM_MACOS_MVK
VK_USE_PLATFORM_METAL_EXT
VK_USE_PLATFORM_VI_NN
VK_USE_PLATFORM_WAYLAND_KHR
VK_USE_PLATFORM_WIN32_KHR
VK_USE_PLATFORM_XCB_KHR
VK_USE_PLATFORM_XLIB_KHR
VK_USE_PLATFORM_DIRECTFB_EXT
VK_USE_PLATFORM_XLIB_XRANDR_EXT
VK_USE_PLATFORM_GGP
VK_USE_PLATFORM_SCREEN_QNX
VK_ENABLE_BETA_EXTENSIONS
This is how I compile in MSYS2
gcc -O0 -g3 -Wall -c -fmessage-length=0 -o "src\\ansi-c.o" "..\\src\\ansi-c.c"
gcc -o ansi-c.exe "src\\ansi-c.o" -lmingw32 -lSDL2main -lSDL2 -lvulkan-1.dll
bcm2835 init works fine, as does all the GPIO & bcm2835_delay and the like.
RPi4 & Pi400, Raspbian "Bullseye", bcm2835 1.71, Libcap installed, added the program name etc
And I've compiled with Geany
gcc -Wall -o "%e" "%f" -pthread $(pkg-config gtk+-3.0 --cflags --libs) -export-dynamic -l bcm2835 -l png -DBCM2835_HAVE_LIBCAP
Here's code:
// bcm_timer.c
//
// Example program for bcm2835 library system time
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <bcm2835.h>
uint64_t now = 0;
uint64_t then = 0;
uint rescode = 0;
int main(int argc, char **argv)
{
// Init GPIO
if ( ! bcm2835_init() )
{
printf("Fail 0x%X ", errno);
return -1;
}
then = bcm2835_st_read();
bcm2835_delay(500);
now = bcm2835_st_read();
printf("Then = 0x%lluX, Now = 0x%lluX \n", then, now) ;
bcm2835_close();
return 0;
}
Here's output:
xxx#raspberrypi:~/Develop/c/test $ ./bcm_timer
Then = 0x0X, Now = 0x0X
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 have the following C File and I am using Mac OS X GCC Compiler.
You find the error below.
#include "support.h"
#ifdef _WIN32
#include <conio.h>
void support_init() {
// not needed
}
void support_clear() {
system("CLS");
}
int support_readkey(int timeout_ms) {
Sleep(timeout_ms);
if (!kbhit()) return 0;
return getch();
}
#else
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <sys/select.h>
void support_init() {
struct termios tio;
tcgetattr(STDIN_FILENO, &tio);
tio.c_lflag &= (~ICANON & ~ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &tio);
}
void support_clear() {
printf("\x1B[2J\x1B[0;0f");
}
int support_readkey(int timeout_ms) {
struct timeval tv = { 0L, timeout_ms * 1000L };
fd_set fds;
FD_ZERO(&fds);
FD_SET(0, &fds);
int r = select(1, &fds, NULL, NULL, &tv);
if (!r) return 0;
return getchar();
}
#endif
And this is my Makefile:
CFLAGS=-std=c11 -Wall -g
CC=clang
all: snake
.PHONY: all clean
snake: snake.o support.o
snake.o: snake.c support.h
clean:
rm -f snake
rm -f snake.o support.o
When I try to compile with the command "make all" I get the following error:
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see
invocation)
Please help. I am new to C :-)
check the Architecture based on that the cflags shoule be updated to set to -m32 or -m64 ,
for successful compilation in 64 bit machine this has to set to -m64.
CFLAGS+= -m64
I'm trying to reproduce an example from Network Security with OpenSSL (by Chandra et al). The program consists of client.c server.c common.h and common.c. client.c simply creates a connection to the server on port 6012 and reads data from stdin and then send those data to the server. The server.c reads data from socket and writes it back out to stdout.
The problem is that server.c always get stuck in if(BIO_do_accept(acc) <= 0) at line 62 and never gets data sent from client.c, which runs perfectly fine. I later found the problem is that pthread_create(...) at line 66 ( which is defined as THREAD_CREATE(...) in common.h) failed and it returned 4294967295. Because THREAD_CREATE(...) failed, the program never get a chance to run do_server_loop in server_thread(...), which explains why the server never got the data from client.
How should I interpret the return values from pthread_create and how should I fix it?
PS. I later used strerror to convert 4294967295 and it returned "Unknown error".
Any help will be much appreciated!
//////////////////////////////////////////////////
Here is server.c:
#include "common.h"
void do_server_loop(BIO *conn)
{
int err, nread;
char buf[80];
do
{
fprintf(stderr, "server_loop executed.\n");
for(nread = 0; nread < sizeof(buf); nread += err)
{
err = BIO_read(conn, buf + nread, sizeof(buf) - nread);
if(err <= 0){
break;
}
}
fwrite(buf, 1, nread, stdout);
}
while (err > 0);
}
void THREAD_CC server_thread(void *arg)
{
fprintf(stderr, "server_thread(void *arg) executed.\n");
BIO *client = (BIO *)arg;
#ifndef WIN32
pthread_detach(pthread_self());
#endif
fprintf(stderr, "Connection opened.\n");
do_server_loop(client);
fprintf(stderr, "Connection closed.\n");
BIO_free(client);
ERR_remove_state(0);
#ifdef WIN32
_endthread();
#else
return 0;
#endif
}
int main(int argc, char *argv[])
{
BIO *acc, *client;
int thread_create_result;
THREAD_TYPE tid;
init_OpenSSL();
acc = BIO_new_accept(PORT);
if(!acc){
int_error("Error creating server socket");
}
if(BIO_do_accept(acc) <= 0){
int_error("Error binding server socket");
}
for(;;)
{
if(BIO_do_accept(acc) <= 0){
int_error("Error accepting connection");
}
client = BIO_pop(acc);
thread_create_result = THREAD_CREATE(tid, server_thread, client);
if(thread_create_result != 0){
fprintf(stderr, "THREAD_CREATE failed! returns: %s.\n", \
strerror(thread_create_result));
fprintf(stderr, "thread_create_result has the value: %u.\n", \
thread_create_result);
exit(-1);
}
}
BIO_free(acc);
return 0;
}
Here is common.h
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/hmac.h>
#include <openssl/objects.h>
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef WIN32
#include <pthread.h>
#define THREAD_CC *
#define THREAD_TYPE pthread_t
#define THREAD_CREATE(tid, entry, arg) pthread_create(&(tid), NULL, \
(entry), (arg))
#else
#include <windows.h>
#include <process.h>
#define THREAD_CC __cdecl
#define THREAD_TYPE DWORD
#define THREAD_CREATE(tid, entry, arg) do { _beginthread((entry), 0, (arg));\
(tid) = GetCurrentThreadId();\
} while (0)
#endif
#define PORT "6012" //port
#define SERVER "10.1.251.24" //server address
#define CLIENT "10.1.21.46" //client address
#define int_error(msg) handle_error(__FILE__, __LINE__, msg)
void handle_error(const char *file, int lineno, const char *msg);
void init_OpenSSL(void);
Makefile:
CC = gcc
OPENSSLDIR = /usr/local/ssl
#CFLAGS = -g -Wall -W -I${OPENSSLDIR}/include -O2 -D_REENTRANT -D__EXTENSIONS__
CFLAGS = -g -Wall -W -I${OPENSSLDIR}/include -O2
RPATH = -R${OPENSSLDIR}/lib
#LD = ${RPATH} -L${OPENSSLDIR}/lib -lssl -lcrypto -lsocket -lnsl -lpthread
LD = -L${OPENSSLDIR}/lib -lssl -lcrypto -lsocket -lnsl -pthread
OBJS = common.o
PROGS = server
all: ${PROGS}
server: server.o ${OBJS}
${CC} server.o ${OBJS} -o server ${LD}
clean:;
${RM} ${PROGS} *.ln *.BAK *.bak *.o
Change
if(thread_create_result = !0){
to
if(thread_create_result != 0){
Besides, you can use strerror function to convert error code to human-readable form.
add -D_REENTRANT on compile command lines and -lpthread on the link command line.
-D_REENTRANT will tell C/C++ libraries that your program is in multithread mode and -lpthread just load the shared library libpthread.so at runtime. I found this at William Garrison's POSIX threads tutorial and this link.
Here is the Makefile:
CC = gcc
OPENSSLDIR = /usr/local/ssl
CFLAGS = -g -Wall -W -I${OPENSSLDIR}/include -O2 -D_REENTRANT -D__EXTENSIONS__
RPATH = -R${OPENSSLDIR}/lib
LD = ${RPATH} -L${OPENSSLDIR}/lib -lssl -lcrypto -lsocket -lnsl -lpthread
OBJS = common.o
PROGS = server
all: ${PROGS}
server: server.o ${OBJS}
${CC} server.o ${OBJS} -o server ${LD}
clean:;
${RM} ${PROGS} *.ln *.BAK *.bak *.o