473,804 Members | 2,154 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

linking C++ functions in a C program

Hi everyone, I'm trying to compile a C++ function and then call it from
a C program.
Since Google is my friend I've ended up to this link which seems very clear:

http://www.parashift.com/c++-faq-lit...c-and-cpp.html

Unfortunately it does not work.
Here is what I'm doing:

-----------------------------------------
//main.c

#include "mylib.h"

int main (int argc, char *argv[]){
foo();
return 0;
}
-----------------------------------------
//mylib.h

#indef __cplusplus
extern "C"{
#endif

void foo();

#ifdef __cplusplus
}
#endif
-----------------------------------------
//mylib.cc

#include <iostream>
#include "mylib.h"

using namespace std; // don't know what for!

void foo(){
cout<<"Hello World!\n";
}
-----------------------------------------
Thanks a lot for any suggestion.

Al
Nov 6 '08
38 2669
Pawel Dziepak <pd******@quarn os.orgwrites:
CBFalconer wrote:
>In general, you just can't do that. C++ function names are
normally altered by the C++ compiler for various reasons. C
function names are not. So the C system can't link the C++ code.

7.5/3 states that: "Every implementation shall provide for linkage to
functions written in the C programming language" by allowing things like
extern "C"
7.5/6 tells us that is is possible to define function with C-style
linkage in C++ code.
7.5/9 informs us that implementation can allow to link objects from
other languages to C++ and from C++ to other languages.

Concluding, C++ standard gives possibility to link C++ functions from C
code (with some naming restrictions).
But if you're imposing restrictions, you're no longer "In general".

Phil
--
We must respect the other fellow's religion, but only in the sense and to the
extent that we respect his theory that his wife is beautiful and his children
smart. -- Henry Louis Mencken (1880-1956), American editor and critic
Nov 7 '08 #21
jameskuyper wrote:
CBFalconer wrote:
.... snip ...
>
>In general, you just can't do that. C++ function names are
normally altered by the C++ compiler for various reasons.

True, but extern "C" turns that off. The only part of his program
compiled with the C++ compiler is a function declared with extern
"C".
They are not compiled with the C++ compiler, they should be
compiled with the C compiler. The object code may be linked with
the C++ linker. The <extern "C"term is only in the .h file that
describes the access to the C code required. In general C++ can
access C code, but C cannot access C++ code.

Remember, the languages are different.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Nov 7 '08 #22
Pawel Dziepak wrote:
CBFalconer wrote:
>In general, you just can't do that. C++ function names are
normally altered by the C++ compiler for various reasons. C
function names are not. So the C system can't link the C++ code.

7.5/3 states that: "Every implementation shall provide for linkage
to functions written in the C programming language" by allowing
things like extern "C"
7.5/6 tells us that is is possible to define function with C-style
linkage in C++ code.
7.5/9 informs us that implementation can allow to link objects from
other languages to C++ and from C++ to other languages.

Concluding, C++ standard gives possibility to link C++ functions
from C code (with some naming restrictions).
You are quoting from, I believe, the C++ standard. My point is
that C cannot call to C++ code, but C++ can call C code. The idea
is to prepare C object code and allow the C++ system to call it
correctly, by using the extern "C" identification _in the header
file for the C code_.

The C++ standard is meaningless in c.l.c. Here, we use the C std.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
Nov 7 '08 #23
Keith Thompson wrote:
CBFalconer <cb********@yah oo.comwrites:
.... snip ...
>
>In general, you just can't do that. C++ function names are
normally altered by the C++ compiler for various reasons. C
function names are not. So the C system can't link the C++ code.

Chuck, we've had this discussion before. Yes, you can call C++
functions from C, and yes, you can call C functions from C++. C++
defines the mechanism for doing this in both directions.

Last time we discussed this, I pointed you to the C++ FAQ that
explains this; it's already been cited in this thread. I even
demonstrated how to do it and posted the output. For some reason you
still didn't believe me, and now you're claiming yet again that it
can't be done.

Please consider the possibility that you might be wrong.
I did. That's why I used the "normally altered" phrase.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.

Nov 7 '08 #24
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

CBFalconer wrote:
You are quoting from, I believe, the C++ standard. My point is
that C cannot call to C++ code, but C++ can call C code. The idea
is to prepare C object code and allow the C++ system to call it
correctly, by using the extern "C" identification _in the header
file for the C code_.
You don't have to use extern "C" in the header file for the C code. C
compilers assume that all functions symbols are in the C style.
extern "C" used in C++ code tell compiler that it has to create C style
symbol for that object (function/variable/whatever), so C code will be
able to call it.
The C++ standard is meaningless in c.l.c. Here, we use the C std.
This discussion is about C *and* C++.

Pawel Dziepak
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org

iEYEARECAAYFAkk TbbEACgkQPFW+cU iIHNpeYQCfSnC6I 6x/PhVfJ3rTN52Lhs+ +
R+MAn09HVzcm7O8 bRrA39QIZwbWUsR 5C
=+D/f
-----END PGP SIGNATURE-----
Nov 7 '08 #25
CBFalconer <cb********@yah oo.comwrites:
Keith Thompson wrote:
>CBFalconer <cb********@yah oo.comwrites:
... snip ...
>>
>>In general, you just can't do that. C++ function names are
normally altered by the C++ compiler for various reasons. C
function names are not. So the C system can't link the C++ code.

Chuck, we've had this discussion before. Yes, you can call C++
functions from C, and yes, you can call C functions from C++. C++
defines the mechanism for doing this in both directions.

Last time we discussed this, I pointed you to the C++ FAQ that
explains this; it's already been cited in this thread. I even
demonstrated how to do it and posted the output. For some reason you
still didn't believe me, and now you're claiming yet again that it
can't be done.

Please consider the possibility that you might be wrong.

I did. That's why I used the "normally altered" phrase.
Please consider the possibility that you might *still* be wrong.

One more time, it is possible to call C functions from C++ code, and
to call C++ functions from C code. The C++ standard defines the
mechanisms for doing this in both directions. Your statement above
that "In general, you just can't do that" is wrong.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 7 '08 #26
James Kuyper <ja*********@ve rizon.netwrites :
Flash Gordon wrote:
>CBFalconer wrote, On 06/11/08 21:54:

If you're responding to what he wrote at that time, why don't you post
it as a response to the message in which he actually wrote it, on the
thread in which he wrote it? It's a little confusing to post it as a
response to a message I wrote, in a thread where he's said some
incorrect things about C/C++ linking, but he hasn't actually said
these particular incorrect things (at least, not yet):
>>describes the access to the C code required. In general C++ can
access C code, but C cannot access C++ code.
James, either I'm confused or you are.

Here's the entire content of what Flash posted, excluding headers and
signature:

| CBFalconer wrote, On 06/11/08 21:54:
|
| <snip>
|
| describes the access to the C code required. In general C++ can
| access C code, but C cannot access C++ code.
| >
| Remember, the languages are different.
|
| Remember, it has been pointed out to you many times and with references
| that you are WRONG. C++ defines how C code can call C++ code and you
| have been shown how it works. Since the theory says it should work and
| practice shows that it works why keep insisting that it does not?
| Neither theory nor practice are on your side.

Flash's article was a direct followup to CBFalconer's article, and
CBFalconer did write exactly the quoted incorrect words:

describes the access to the C code required. In general C++ can
access C code, but C cannot access C++ code.

Remember, the languages are different.

Did the "06/11/08" date format throw you off? It's DD/MM/YY, not
MM/DD/YY -- i.e., it's today, not 5 months ago. (MM/DD/YY is more
common in the US, DD/MM/YY in the UK; that's why I use YYYY-MM-DD
whenever possible.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 7 '08 #27
CBFalconer wrote:
jameskuyper wrote:
>CBFalconer wrote:
... snip ...
>>In general, you just can't do that. C++ function names are
normally altered by the C++ compiler for various reasons.
True, but extern "C" turns that off. The only part of his program
compiled with the C++ compiler is a function declared with extern
"C".

They are not compiled with the C++ compiler, they should be
compiled with the C compiler. ...
The purpose of the exercise was to find out how to call code compiled by
C++ from code compiled in C. How would compiling them with C serve that
purpose?
... The object code may be linked with
the C++ linker. The <extern "C"term is only in the .h file that
describes the access to the C code required. In general C++ can
access C code, but C cannot access C++ code.

Remember, the languages are different.
Yes, they are different languages - so what?. C++ defines features that
allow C++ code to call C code, and to define C++ functions that can be
called from C.

The program below contains a function named bar() compiled by C++ with
"C" language linkage. I know from previous discussions with you that you
have said some confusing things about whether you consider such a
function to be a C function or a C++ function.

Rather than repeat my previous failed attempts to get a straight answer
out of you about that question, I've written a program that contains one
function named foo() which is compiled in C, and is therefore
unambiguously a C function. It contains another function named baz()
compiled in C++ that has "C++" language linkage, so it is unambiguously
a C++ function. foo() calls bar() which calls baz(). Therefore, no
matter how you classify bar(), this program contains a C function
calling a C++ function.

foobar.h:
=============== =========
#ifndef FOOBAR_H
#define FOOBAR_H

#ifdef __cplusplus
extern "C" {
#endif

void foo(int);
void bar(int);

#ifdef __cplusplus
}
#endif
#endif
foo.c:
=============== =============== =====
#include <stdio.h>
#include "foobar.h"

void foo(int i) {
puts("About to call bar()");
bar(i);
puts("Finished calling bar()");
}

main.C
=============== =============== =============== =====
#include <iostream>
#include "foobar.h"

int main()
{
foo(42);
}

static void baz(int i)
{
std::cout << "the number is:" << i << std::endl;
}

void bar(int i)
{
baz(i);
}

I built the complete program as follows:

~/testprog/CfromC++(63) gcc $CFLAGS -c foo.c
In file included from foo.c:2:

~/testprog/CfromC++(64) !g++
g++ $CXXFLAGS main.C foo.o -o foobar

~/testprog/CfromC++(65) printenv CFLAGS
-std=c99 -pedantic -Wall -Wpointer-arith -Wcast-align -Wwrite-strings
-Wstrict-prototypes -Wmissing-prototypes

~/testprog/CfromC++(66) printenv CXXFLAGS
-std=c++98 -pedantic -Wall -Wpointer-arith -Wcast-align
-fno-enforce-eh-specs -ffor-scope -fno-gnu-keywords
-fno-nonansi-builtins -Wctor-dtor-privacy -Wnon-virtual-dtor
-Wold-style-cast -Woverloaded-virtual -Wsign-promo

~/testprog/CfromC++(67) foobar
About to call bar()
the number is:42
Finished calling bar()

If, as you say, C cannot access C++ code, then what exactly is the above
program doing when foo() calls bar() which calls baz()?
Nov 7 '08 #28
Keith Thompson wrote:
James Kuyper <ja*********@ve rizon.netwrites :
>Flash Gordon wrote:
>>CBFalconer wrote, On 06/11/08 21:54:
If you're responding to what he wrote at that time, why don't you post
it as a response to the message in which he actually wrote it, on the
thread in which he wrote it? It's a little confusing to post it as a
response to a message I wrote, in a thread where he's said some
incorrect things about C/C++ linking, but he hasn't actually said
these particular incorrect things (at least, not yet):
>>>describes the access to the C code required. In general C++ can
access C code, but C cannot access C++ code.

James, either I'm confused or you are.
I am the one who was confused, but it's my news server's fault, not
mine. My news server got Flash's message before it got CBFalconer's
message, and my newsreader displayed Flash's message as a response to my
message.

Another part of the confusion is the notation 06/11/08. I normally use
an ISO format time: 2008-11-06. It is one of the two permitted date
format on the project where I work, but I was a fan of that format
before I ever joined this project. As a result, I misread 06/11/08 as
referring to 2006-11-08.

My message reflected irritation that wasn't caused entirely by my
misinterpretati on of this one message from Flash. I knew from previous
experience that CBFalconer doesn't believe that C++ functions can be
called from C, so ever since he entered this thread I've been itching to
show him a counter-example. However, until this particular message, he
had failed to state his position in a way that made my counter-example
directly relevant. I was getting a bit frustrated waiting for him to say
something I could respond to. Then Flash's message showed up quoting
CBFalconer saying something directly relevant - I could finally post my
counter-example! However, I then noticed that the message Flash referred
to was not displayed by my newsreader, and that Flash's message referred
to a date which I misinterpreted as being from 2 years ago, so I felt a
bit disappointed.

I apologize for the confusion I passed on, and for the irritation I
expressed.
Nov 7 '08 #29
CBFalconer wrote:
Pawel Dziepak wrote:
>CBFalconer wrote:
....
You are quoting from, I believe, the C++ standard. My point is
that C cannot call to C++ code, but C++ can call C code.
Yes, and that point is incorrect, as demonstrated by a response I just
posted in another branch of this discussion.
... The idea
is to prepare C object code and allow the C++ system to call it
correctly, by using the extern "C" identification _in the header
file for the C code_.
Actually, the extern "C" should only appear in the C++ code. You can put
it in C code only by using conditional compilation to ensure that it
doesn't survive translation phase 4.
The C++ standard is meaningless in c.l.c. Here, we use the C std.
Since it is the C++ standard that defines how to link C code to C++
code, this discussion should have been posted to a C++ group. However,
just because the C++ standard is off-topic here doesn't mean that it
doesn't exist, and it doesn't justify making statements here be which
would be true only if it didn't exist. The C++ standard does indeed
define how to create a function compiled in C++, the body of which can
make full use of all C++ features, but callable from C.
Nov 7 '08 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
2591
by: Jeff Hagelberg | last post by:
I'm trying to create a python module which can be used by a python interpreter embedded inside a fortran program I have. To do this, I first created python wrappers for all the functions in my fortran program using f2py. I then start an embedded python interpreter in c code which I link against the fortran program. I invoke the fortran program with a filename containing python code. This file is passed to the c code which passes it on...
7
5127
by: Steven T. Hatton | last post by:
Is there anything that gives a good description of how source code is converted into a translation unit, then object code, and then linked. I'm particularly interested in understanding why putting normal functions in header files results in multiple definition errors even when include guards are used. -- STH Hatton's Law: "There is only One inviolable Law" KDevelop: http://www.kdevelop.org SuSE: http://www.suse.com Mozilla:...
20
3245
by: Steven T. Hatton | last post by:
I just read this in the description of how C++ is supposed to be implemented: "All external object and function references are resolved. Library components are linked to satisfy external references to functions and objects not defined in the current translation. All such translator output is collected into a program image which contains information needed for execution in its execution environment." What I'm wondering is what exactly...
1
6099
by: Venky | last post by:
I'm compiling a C program that is using Interbase 6.0 APIS. Getting the following errors at the time of linking. Linking test.exe: Linker Warning: No module definition file specified: using defaults Linker Error: Undefined symbol isc_detach_database in module TEST.C ..... ..... If I set the option not to generate the underscore (function prefixed with "_") I get the following errors. Interbase 6.0 APIs resolved
1
313
by: Peetah_junkmail | last post by:
Hi, I'm not sure this is completely a C related question since it's more about linking problems, so don't hesitate to redirect me to a more appropriate NG. I have a set of useful functions (let's call this SUF) that facilitates my life when coding, such as memory allocation wrappers or generic string functions. I have a project composed of a shared library (SL) and a main program (MP) using SL. For some reasons, I don't want to make a...
3
3529
by: Kevin Burton | last post by:
I am trying to use managed C++ but I am getting the following link errors: Metadata file 'D:\Projects\Visa\AddressVerification\AddressVerificat ionTest\bin\Debug\AddressVerificationInterface.dll' could not be found AddressVerificationInterface error LNK2001: unresolved external symbol "void * __cdecl operator new(unsigned int)" (??2@$$FYAPAXI@Z)
3
4376
by: walkeraj | last post by:
I'm trying to compile an open source game called IVAN , and I'm able to compile it from a makefile, but not from an IDE. I have attempted to recreate the way the makefile compiles the project as closely as possible, yet I'm getting odd linking errors. I think I've traced it to some kind of problem with the SDL libraries it uses, yet I can't explain why it will compile from the makefile and not from the IDE. I have made sure that the ide...
6
2494
by: Joe.pHsiao | last post by:
Hi, I tried to link a C program to a library which is written by me in C+ +. I read some posts about linking a C program to C++ libraries. It seems doable by adding extern "C" to the C++ head file and to the function body modifier. However, in my test, it still doesn't work. The linking error messages are like undefined reference for new operator, and undefined reference from dequeue.tcc. ( sorry I don't know how to copy lines from...
10
2201
kiseitai2
by: kiseitai2 | last post by:
Hi everyone. My problem is tha Dev-C++ compiles perfectly fine but it fails in the linking process. I receive the linker error "multiple definitions of"; howerver, I modified the names of the functions in three of the files, checked my code to make sure I wasn't redefining my functions, changed code back and forth from .cpp to .h, and even excluded some files from the project and included them manually. Also, I even recopied the lines of code...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10341
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10089
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9171
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7634
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6862
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.