C++ version
#include <iostream>
int main(){
std::cout << "Hello World" << std::endl;
}
C version
#include <stdio.h>
int main(){
puts("Hello World");
return 0;
}
for C++
g++ main.cpp -o main
for C
gcc main.c -o main
for C++
linux-vdso.so.1 (0x00007ffc026df000)
libstdc++.so.6 => /usr/lib/gcc/x86_64-pc-linux-gnu/13/libstdc++.so.6 (0x00007f5fdc600000)
libm.so.6 => /lib64/libm.so.6 (0x00007f5fdc863000)
libgcc_s.so.1 => /usr/lib/gcc/x86_64-pc-linux-gnu/13/libgcc_s.so.1 (0x00007f5fdc5db000)
libc.so.6 => /lib64/libc.so.6 (0x00007f5fdc402000)
/lib64/ld-linux-x86-64.so.2 (0x00007f5fdc965000)
for C
linux-vdso.so.1 (0x00007ffd509f5000)
libc.so.6 => /lib64/libc.so.6 (0x00007f6fce003000)
/lib64/ld-linux-x86-64.so.2 (0x00007f6fce1ff000)
for C++: 270
for C: 248
for C++: 16032
for C: 15480
for C++: 10
for C: 6
OOP suppoted.
class test {
private:
double value;
public:
test(double l) {
value = l;
}
}
void main(){
test t(12);
t.value = 23;
}
OOP is not supported but we can use struct.
typedef struct _test {
double value;
} test;
test* test_new(double l){
test *ctx;
ctx->value = l;
return ctx;
}
void main(){
test *t = test_new(12);
t->value = 23;
}
extern "C" {
// Write C code here
}
- Create header in C
#ifdef __cplusplus
extern "C" {
#endif
typedef void* test;
test test_new(double l);
void test_set_value(test* ctx, double l);
double test_get_value(test* ctx);
#ifdef __cplusplus
}
#endif
- create wrapper in C++
#include <test>
extern "C" {
test test_new(double l){
Test* t = new Test(l);
return (test) t;
}
void test_set_value(test* ctx, double l){
Test* t = (Test*)ctx;
t->value = l;
}
double test_get_value(test* ctx){
Test* t = (Test*)ctx;
return t->value;
}
}
- compile like this
g++ test.cpp -c -o test.o
gcc main.c -c main.o
gcc main.o test.o -o main -lstdc++
Supported
try {
// buggy code here
} catch(const std::exception& e) {
// write message here
}
Not supported but we can use setjmp
#include <stdio.h>
#include <signal.h>
#include <setjmp.h>
jmp_buf env;
#define try \
int ret = setjmp(env); \
if (ret == 0) {
#define catch(exception) \
} else if (ret == exception) {
#define throw(exception) \
longjmp(env, exception)
#define endtry }
#define FloatingPointException 1
void handle_floating_exception(){
throw(FloatingPointException);
}
int main() {
// Install signal handler for division by zero
signal(SIGFPE, handle_floating_exception);
try {
int a = 10;
int b = 0;
printf("Attempting division by zero\n");
int result = a / b; // Division by zero
printf("This won't be executed\n");
}
catch(FloatingPointException) {
printf("Handled floating point exception\n");
} endtry
return 0;
}