I tried running this sample code from fm4dd.com. But I don't know how to actually include the header files into my program.
Orignally it was like:
#include <openssl/bio.h>
But i changes it to their actual path, but an error still shows up.
#include <C:\openssl\include\openssl\bio.h>
#include <C:\openssl\include\openssl\err.h>
#include <C:\openssl\include\openssl\pem.h>
#include <C:\openssl\include\openssl\x509.h>
#include <C:\openssl\include\openssl\e_os2.h>
int main() {
const char cert_filestr[] = "./cert-file.pem";
EVP_PKEY *pkey = NULL;
BIO *certbio = NULL;
BIO *outbio = NULL;
X509 *cert = NULL;
int ret;
/* ---------------------------------------------------------- *
* These function calls initialize openssl for correct work. *
* ---------------------------------------------------------- */
OpenSSL_add_all_algorithms();
ERR_load_BIO_strings();
ERR_load_crypto_strings();
/* ---------------------------------------------------------- *
* Create the Input/Output BIO's. *
* ---------------------------------------------------------- */
certbio = BIO_new(BIO_s_file());
outbio = BIO_new_fp(stdout, BIO_NOCLOSE);
/* ---------------------------------------------------------- *
* Load the certificate from file (PEM). *
* ---------------------------------------------------------- */
ret = BIO_read_filename(certbio, cert_filestr);
if (! (cert = PEM_read_bio_X509(certbio, NULL, 0, NULL))) {
BIO_printf(outbio, "Error loading cert into memory\n");
exit(-1);
}
/* ---------------------------------------------------------- *
* Extract the certificate's public key data. *
* ---------------------------------------------------------- */
if ((pkey = X509_get_pubkey(cert)) == NULL)
BIO_printf(outbio, "Error getting public key from certificate");
/* ---------------------------------------------------------- *
* Print the public key information and the key in PEM format *
* ---------------------------------------------------------- */
/* display the key type and size here */
if (pkey) {
switch (pkey->type) {
case EVP_PKEY_RSA:
BIO_printf(outbio, "%d bit RSA Key\n\n", EVP_PKEY_bits(pkey));
break;
case EVP_PKEY_DSA:
BIO_printf(outbio, "%d bit DSA Key\n\n", EVP_PKEY_bits(pkey));
break;
default:
BIO_printf(outbio, "%d bit non-RSA/DSA Key\n\n", EVP_PKEY_bits(pkey));
break;
}
}
if(!PEM_write_bio_PUBKEY(outbio, pkey))
BIO_printf(outbio, "Error writing public key data in PEM format");
EVP_PKEY_free(pkey);
X509_free(cert);
BIO_free_all(certbio);
BIO_free_all(outbio);
exit(0);
}
but the following error shows up every time I try to compile it on the command prompt. Since, I'm a noob, I have no clue how to proceed from here and what to do to fix this error.
c:\openssl>gcc -lssl -lcrypto -o test test.c
In file included from test.c:1:0:
C:\openssl\include\openssl\bio.h:62:27: fatal error: openssl/e_os2.h: No such file or directory
#include <openssl/e_os2.h>
^
compilation terminated.
Edit:
I included the solution to the problem, but now a new error showed up:
c:\openssl>gcc -lssl -lcrypto -o test test.c -IC:\openssl\include\
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: cannot find -lssl
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/bin/ld.exe: cannot find -lcrypto
collect2.exe: error: ld returned 1 exit status
In many cases, include-files in turn include other files. The paths of these files are specified relative, not absolute. So you have to tell your compiler, where to search for include files in general.
The -I-option is for this purpose and tells the compiler, which paths (additionally to some standard paths) are to be searched for specified include files, in your case you would use:
gcc -I C:\openssl\include
If you really need to specify an absolute include path you would use quotes, not <>, i.e.
#include "C:\foo\bar\baz.h"
but if this file includes other files, the compiler will not look specifically into C:\foo\bar for these.
Get rid of the full path names in your #include directives. That is, don't use #include <C:\openssl\include\openssl\bio.h>; rather, use:
#include <openssl\bio.h>
#include <openssl\err.h>
#include <openssl\pem.h>
#include <openssl\x509.h>
#include <openssl\e_os2.h>
And pass the include directory to gcc with -I:
gcc -I c:\openssl\include -o myfile myfile.c -lcrypto
I am trying to use two .c files together. I am lost at how to do this, I have a simple setup for each file but I get a undefined reference to format_lines error when I try to compile. Any help would be muchly appreciated;
formatter.h
#ifndef _FORMATTER_H_
#define _FORMATTER_H_
#include <stdio.h>
char **format_file(FILE *);
char **format_lines(char **, int);
void test();
#endif
formatter.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "formatter.h"
char **format_file(FILE *infile) {
return NULL;
}
char **format_lines(char **lines, int num_lines) {
char **result = NULL;
#ifdef DEBUG
result = (char **)malloc(sizeof(char *) * 2);
if (result == NULL) {
return NULL;
}
result[0] = (char *)malloc(sizeof(char) * 80);
if (result[0] == NULL) {
return NULL;
}
strncpy(result[0], "(machine-like voice) EXTERMINATE THEM!", 79);
result[1] = (char *)malloc(sizeof(char) * 2);
if (result[1] == NULL) {
return NULL;
}
result[1][0] = '\0';
#endif
}
void test(){
print("here");
}
and sengfmt.c
#include <stdio.h>
#include <stdlib.h>
#include "formatter.h"
int main(int argc, char *argv[]) {
test();
#ifdef DEBUG
printf("%s does nothing right now.\n", argv[0]);
#endif
exit(0);
}
When I try to compile, I just type this.
$ gcc sengfmt3.c
/tmp/cc7Ttgne.o: In function `main':
sengfmt3.c:(.text+0x15): undefined reference to `test'
collect2: ld returned 1 exit status
I suspect that your main used to try to call format_lines
You need to do this
gcc formatter.c sendgfmt.c -o myprog
You must list all the c files that you want compiled together
If you have code in multiple source files, then you need to build with all the source files.
There are two ways of doing this:
Compile and link all source files using using one command:
$ gcc sengfmt3.c someOtherSourceFile.c someThirdSourceFile.c
First make object files of all source files, and then link the object files together. This is more work, but if you have a makefile or other build-system it will be better since only the modified source files will be recompiled, and might save you some build-time:
$ gcc -c sengfmt3.c
$ gcc -c someOtherSourceFile.c
$ gcc -c someThirdSourceFile.c
$ gcc sengfmt.o someOtherSourceFile.o someThirdSorceFile.o
Note the command-line option -c for the compilation, this tells GCC to generate object files. Also note that for the linking command (the last one) the file extensions have changed from .c to .o.
The command in point 1 does this internally, using temporary files which are removed when done.
Below is an attempt to write basic multi-threaded program where each thread will read one line from a log file (and does nothing). There is a bug somewhere and program segfaults (no core file generated).
If fgets() is replaced by fscanf() in readInput() then I see a core file. Backtrace is inconsistent and gives different call stack in different core file.
Contents of log file look like:
<num> hello<num>
all numbers less than 100
There are about 90 entries in the log file.
AFAIK, for what this code is doing, we don't need locks. But I put it for later use (and practice).
Can someone please point my mistakes in this code?
threads.h
---------
#include "../../include/global.h"
#include <pthread.h>
#define MAX_LOGS 101
#define NUM_THREADS 10
/* a single record in log file. Read by thread from input stream (file) */
typedef struct __thread_data {
int time; /* time stamp */
char log[32]; /* short log msg */
} thread_data_t;
/* heap (implemented by ordered array) storing the logs */
typedef struct __heap {
thread_data_t entry[MAX_LOGS];
int cur_size; /* used while inserting nodes? */
} heap_t;
add.c
-----
#include "../include/threads.h"
/* Stream from which logs are read (file stream here). Only one thread can
* read at a time */
FILE *fp;
pthread_mutex_t fp_lock;
/* thread start routine */
void *readInput(void *arg)
{
char log[40];
/* get lock for file read */
pthread_mutex_lock(&fp_lock);
/* Critical Section; read file */
if(!feof(fp)) {
fgets(log, 40, fp);
}
/* release lock */
pthread_mutex_unlock(&fp_lock);
pthread_exit(NULL);
}
int pthread_main()
{
int i, ret;
pthread_t threads[NUM_THREADS];
pthread_mutex_init(&fp_lock, NULL);
fp = fopen("logs.txt", "r");
/* error check */
for(i=0; i<NUM_THREADS; i++) {
if(ret = pthread_create(&threads[i], NULL, readInput, NULL)) {
printf("Oops: %s\n", strerror(ret));
return EXIT_FAILURE;
}
}
for(i=0; i<NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
fclose(fp);
return EXIT_SUCCESS;
}
test.c
-------
#include "../include/threads.h"
int main()
{
return pthread_main();
}
Makefile
---------
CC = gcc
CFLAGS = -pthread
OBJFLAGS = -o
STDFLAGS = -std=c99
DBGS = -ggdb -pthread
OBJS = add.o test.o
HEADERS = include/threads.h
SOURCES = src/add.c src/test.c
all: $(OBJS)
$(CC) $(OBJFLAGS) th $(OBJS)
#make clean
$(OBJS): $(SOURCES) $(HEADERS)
$(CC) -c $(DBGS) $(SOURCES)
.PHONY: clean
clean:
rm -rf *.o
Backtrace of core dump.
#0 0x00007fff88d5b68e in pthread_create ()
(gdb) bt
#0 0x00007fff88d5b68e in pthread_create ()
#1 0x00000001051e0cf8 in pthread_main () at add.c:46
#2 0x00000001051e0dbf in main () at test.c:5
(gdb) list
1 #include "../include/threads.h"
2
3 int main()
4 {
5 pthread_main();
6 return 0;
7 }
(gdb) info thread
error on line 787 of "/SourceCache/gdb/gdb-1824/src/gdb/macosx/macosx-nat-infthread.c" in function "void print_thread_info(thread_t, int *)": (ipc/send) invalid destination port (0x10000003)
(gdb) info threads
5 0x00007fff88d47194 in thread_start ()
4 0x00007fff8a15e122 in __psynch_mutexwait ()
3 0x00007fff8a15e122 in __psynch_mutexwait ()
2 0x00007fff88dc242b in flockfile ()
* 1 0x00007fff88d5b68e in pthread_create ()
EDIT1: Thanks for all your feedback. I wanted to keep the actual code concise in original post. But here are the .c and .h files and also the Makefile I am using.
EDIT2: Adding backtrace of core. Line 46 in add.c is pthread_create() routine.
Problem lies in fopen. Code compiles, links and creates an executable correctly. When running it, it failed to open the log file as it could not locate it. I have below file/directory structure. Comment made by #self helped identify the issue.
src/
| Makefile
+--include/
| | threads.h
|
+--src/
| add.c
| test.c
| logs.txt
Either one of the following resolves the issue: (a) Changing the make rule to build executable in src directory and running it that directory. (b) Keep make rule as is but change fopen to point to src/logs.txt.
From the documentation: http://luajit.org/running.html
luajit -b test.lua test.obj # Generate object file
# Link test.obj with your application and load it with require("test")
But doesn't explain how to do these things. I guess they're assuming anyone using Lua is also a C programmer, not the case with me! Can I get some help? GCC as an example.
I would also like to do the same thing except from the C byte array header. I can't find documentation on this either.
luajit -bt h -n test test.lua test.h
This creates the header file but I don't know how to run it from C. Thanks.
main.lua
print("Hello from main.lua")
app.c
#include <stdio.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
int main(int argc, char **argv)
{
int status;
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "require");
lua_pushliteral(L, "main");
status = lua_pcall(L, 1, 0, 0);
if (status) {
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
return 0;
}
Shell commands:
luajit -b main.lua main.o
gcc -O2 -Wall -Wl,-E -o app app.c main.o -Ixx -Lxx -lluajit-5.1 -lm -ldl
Replace -Ixx and -Lxx by the LuaJIT include and library directories. If you've installed it in /usr/local (the default), then most GCC installations will find it without these two options.
The first command compiles the Lua source code to bytecode and embeds it into the object file main.o.
The second command compiles and links the minimal C application code. Note that it links in the embedded bytecode, too. The -Wl,-E is mandatory (on Linux) to export all symbols from the executable.
Now move the original main.lua away (to ensure it's really running the embedded bytecode and not the Lua source code file) and then run your app:
mv main.lua main.lua.orig
./app
# Output: Hello from main.lua
The basic usage is as follows:
Generate the header file using luajit
#include that header in the source file(s) that's going to be referencing its symbols
Compile the source into a runnable executable or shared binary module for lua depending on your use-case.
Here's a minimal example to illustrate:
test.lua
return
{
fooprint = function (s) return print("from foo: "..s) end,
barprint = function (s) return print("from bar: "..s) end
}
test.h
// luajit -b test.lua test.h
#define luaJIT_BC_test_SIZE 155
static const char luaJIT_BC_test[] = {
27,76,74,1,2,44,0,1,4,0,2,0,5,52,1,0,0,37,2,1,0,16,3,0,0,36,2,3,2,64,1,2,0,15,
102,114,111,109,32,102,111,111,58,32,10,112,114,105,110,116,44,0,1,4,0,2,0,5,
52,1,0,0,37,2,1,0,16,3,0,0,36,2,3,2,64,1,2,0,15,102,114,111,109,32,98,97,114,
58,32,10,112,114,105,110,116,58,3,0,2,0,5,0,7,51,0,1,0,49,1,0,0,58,1,2,0,49,1,
3,0,58,1,4,0,48,0,0,128,72,0,2,0,13,98,97,114,112,114,105,110,116,0,13,102,
111,111,112,114,105,110,116,1,0,0,0,0
};
runtest.cpp
// g++ -Wall -pedantic -g runtest.cpp -o runtest.exe -llua51
#include <stdio.h>
#include <assert.h>
#include "lua.hpp"
#include "test.h"
static const char *runtest =
"test = require 'test'\n"
"test.fooprint('it works!')\n"
"test.barprint('it works!')\n";
int main()
{
lua_State *L = luaL_newstate();
luaL_openlibs(L);
lua_getglobal(L, "package");
lua_getfield(L, -1, "preload");
// package, preload, luaJIT_BC_test
bool err = luaL_loadbuffer(L, luaJIT_BC_test, luaJIT_BC_test_SIZE, NULL);
assert(!err);
// package.preload.test = luaJIT_BC_test
lua_setfield(L, -2, "test");
// check that 'test' lib is now available; run the embedded test script
lua_settop(L, 0);
err = luaL_dostring(L, runtest);
assert(!err);
lua_close(L);
}
This is pretty straight-forward. This example takes the byte-code and places it into the package.preload table for this program's lua environment. Other lua scripts can then use this by doing require 'test'. The embedded lua source in runtest does exactly this and outputs:
from foo: it works!
from bar: it works!
I have this c program:
#include <sys/types.h>
#include "ourhdr.h"
int glob = 6; /* external variable in initialized data */
char buf[] = "a write to stdout\n";
int
main(void)
{
int var; /* automatic variable on the stack */
pid_t pid;
var = 88;
if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
err_sys("write error");
printf("before fork\n"); /* we don't flush stdout */
if ( (pid = fork()) < 0)
err_sys("fork error");
else if (pid == 0) { /* child */
glob++; /* modify variables */
var++;
} else
sleep(2); /* parent */
printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
exit(0);
}
In the header file "ourhdr.h" (located in the same folder) i defined several functions, such as err_sys().
I get this error while compiling with gcc:
In function "main":
undefined reference to "err_sys"
How can i get this working? I can post the header file here if needed. Thank you.
** EDIT: ** This is the ourhdr.h file: http://pastebin.com/fMUiG4zU
You have included the header file with the declaration of err_sys. Ensure you have also an implementation that is passed to the linker. Background:
The compiler compiles a module to an object file:
g++ -c modul1.c generates modul1.o
g++ -c modul2.c generates modul2.o
Each of the modules can reference functions that are defined in a included header file. Up to here, no actual implementation of that function is needed.
In the next step, the linker links toghether all object files (and libraries):
g++ modul1.o modul2.o generates ./a.out or similar
In the second step, an implementation for all used functions is needed. Be sure you provided it!
(P.S.: Some compilers allow compiling and linking with one command, if you have multiple modules you can perhaps add them to a single gcc-call. I'd recomment to use make though)
I think what's likely to happen is that you have a header, ourhdr.h, containing the definition of the function, but the implementation is in a different file: ourhdr.c. In that case, if you try to compile without including ourhdr.c you'll get a reference error:
$ gcc main.c
/bin/ld: /tmp/ccVzNF6w.o: in function `main':
main.c:(.text+0x38): undefined reference to `err_sys'
To fix it, you need to compile like this:
$ gcc main.c ourhdr.c
Another option is to define the body of the function in ourhdr.h:
// ourhdr.h
#include <stdio.h>
void err_sys(const char* str);
void err_sys(const char* str) {
fprintf(stderr, "%s\n", str);
}
In that case, gcc main.c should work.
For me, it is compiling and working fine if you write the function name is written correctly.