Skip to content
Snippets Groups Projects
Commit 535964aa authored by Jake Feddersen's avatar Jake Feddersen
Browse files

Notes and assignment submission and stuff

parent 469ced8a
No related branches found
No related tags found
No related merge requests found
File added
File added
#include "header.h"
int main(int argc, char *argv[]) {
ostream *o;
cpp_function("Hello World");
o = return_printer();
print(o, "Hello World!");
return 0;
}
File added
#include <iostream>
#include "header.h"
using namespace std;
void cpp_function(const char *s)
{
cout << s << endl;
}
ostream *return_printer() {
return &cout;
}
void print(ostream *o, const char *s) {
*o << s << endl;
}
File added
#ifndef HEADER_H
#define HEADER_H
#ifdef __cplusplus
// This code is only seen by the C++ compiler
#include <iostream>
using namespace std;
extern "C" {
#else
// This code is only seen by the C compiler
typedef void ostream;
#endif
void cpp_function(const char *s);
ostream *return_printer();
void print(ostream *o, const char *s);
#ifdef __cplusplus
}
#endif
#endif
c++ uses name mangling; c doesn't. Name mangling is necessary in order to
allow function overloading. Mangled names encode the formal parameters so
that the compiler can shoose the right function based on the arguments.
In order for c++ to make calls to C functions or vice versa, it's necessary
to tell the c++ compiler not to mangle the names. We'll need this with any
functions that we wish to call in both C and C++. When compiling with a
C++ compiler, you tell the com;iler to use a C calling convention (no name
mangling) by declaring the function 'extern "C"', or by putthing the
declaration inside an 'extern "C"' block. Usually this is done with the
following construction:
#ifdef __cplusplus
extern "C" {
#endif
/* Prototpyes of functions that you want to use in C and C++ */
#ifdef __cplusplus
}
#endif
C doesn't know anything about 'extern "C"', so the guards around this block
ensure that when you include this header in C code, that extra stuff is
stripped out by the preprocessor, but when used in C++ code, it remains.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment