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
CBFalconer wrote, On 07/11/08 08:32:
Flash Gordon wrote:
>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.
I sent some answers, but something has fouled, and they are not
here.
The still quoted text by you above was part of one of your answers you
posted which was wrong. It was EXPLICITLY the quoted text I was refering
to where your answer was wrong but a redirection would have been
appropriate. So instead of the above quoted material you should either
have posted nothing or you should have posted a redirection. Any other
answers you might have posted are irrelevant unless they were also
erroneous and should have been redirections.
--
Flash Gordon
If spamming me sent it to sm**@spam.cause way.com
If emailing me use my reply-to address
See the comp.lang.c Wiki hosted by me at http://clc-wiki.net/
Phil Carmody wrote:
Ian Collins <ia******@hotma il.comwrites:
>abasili wrote:
>>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
Unfortunate ly it does not work.
It does if you follow all the points. The first two are often overlooked.
Some would say it's impossible. If you are building the final
executable (main and linking) with a C++ compiler, then they
might say that you are building a C++ program that calls C
functions. However, what was required was instead a C program
which calls C++ functions. If you're careful to avoid anything
too C++-like, then C++ can be incorporated into C, but then
you're hamstrung a bit with what you can do in C++, and what's
the point. So I'd say stick C into C++, not the other way round.
Once you have mixed C and C++ source into the same program, it is no
longer a "C program" or a "C++ program", if indeed it ever was.
It is possible to call C functions from C++ functions. It is possible
to call C++ functions from C functions. It is possible to link C and
C++ functions into the same program. All that remains for discussion is
either (a) how to accomplish it, or (b) declaring it off-topic for
comp.lang.c.
S
In article <LO************ ****@nwrddc01.g nilink.net>,
James Kuyper <ja*********@ve rizon.netwrote:
>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.
Blame that on the newsreader[1], not the newsswerver. Newsreaders
should be able to tell that there's an article missing, if a followup
to that article appears (and has a correct References header, which it
did on my newsserver).
An example of a sensible way to handle it:
My newsreader (trn) displays a nice ascii-art tree of the thread:
+-(1)--(1)+-(1)+-(1)--(1)+-(1)
| | | \-[1]
| | \-(1)--(1)
| \-(1)
|-(1)+-(1)+-(1)
If there's an article missing but there is a follow-up to it, the
newsreader can tell that there should be something there (from the
references header in the followups), and it will draw a hole in the
tree in the appropriate place:
+-(1)--( )+-(1)+-(1)--(1)+-(1)
^^^
If I try to go from an article to a missing parent it will tell me
"This article is not available" instead of just skipping it and going
to the next available parent.
dave
[1] The software used to read news, not (at least in this case) the
person reading news.
--
Dave Vandervies dj3vande at eskimo dot com
On my machine, the C++ version is very fast, and crashes much quicker than
Scheme.
--William D Clinger in comp.lang.schem e
James Kuyper wrote:
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.
You weren't the only one. Something went wrong somewhere yesterday.
--
Ian Collins
James Kuyper wrote:
CBFalconer wrote: Various incorrect things.
.... snip ...
>
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 concede my posts have not been accurate. I still don't think C
calling C++ is convenient, accurate, and really useful, although
possible. In the above:
foobar.h sets up definitions of foo and bar that requires them to
be called without name adornment The actual code is implemented in
the C++ file (.cpp would be more descriptive than .C, IMO). I
guess the compiler can generate two references to foo, one adorned,
and one not adorned, although that is an unnecessary complication.
Some confusion: Note that the code for bar is compiled with a C++
compiler. Thus it must follow C++ rules, for such things as
reserved names, size of char constants, etc. It can thus make a
great difference if bar is moved to a .c file, #includes
"foobar.h", and totally removed from main.C. To me, this is a
cleaner organization, and ensures that C code is compiled as C, and
C++ code is compiled as C++. Conceded, it will prevent using
std::cout etc.
I think I have avoided confusing my biases with facts here :-)
--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
CBFalconer wrote:
....
I concede my posts have not been accurate. I still don't think C
calling C++ is convenient, accurate, and really useful, although
possible. In the above:
foobar.h sets up definitions of foo and bar that requires them to
be called without name adornment The actual code is implemented in
the C++ file (.cpp would be more descriptive than .C, IMO). ...
? - The actual code for foo() is in the C file.
... I
guess the compiler can generate two references to foo, one adorned,
and one not adorned, although that is an unnecessary complication.
I know of no way to tell the either compiler to do so, nor any reason
to want to. Both functions are callable without adornment from
anywhere that their declarations from foobar.h are in scope.
Some confusion: Note that the code for bar is compiled with a C++
compiler. Thus it must follow C++ rules, for such things as
reserved names, size of char constants, etc. It can thus make a
great difference if bar is moved to a .c file, #includes
"foobar.h", and totally removed from main.C.
Well, the whole purpose of bar() is to be callable from C code, while
having access to C++ functionality. It would lose that access if were
moved to the .c file. It's sort of like saying: that bridge would be
much less likely to fall in the river if you moved it over onto the
west bank. The point of the bridge is to cross that river, and the
point of bar() is to enable communication between the C and C++ parts
of the program.
... To me, this is a
cleaner organization, and ensures that C code is compiled as C, and
C++ code is compiled as C++. Conceded, it will prevent using
std::cout etc.
Yes, thereby defeating the whole purpose of the code. This is just a
simplified example, a more realistic example would involve linking
together two different libraries, one written in C, one written in C+
+, and making use of both libraries from within a single program.
Clearly, either library could be rewritten in the other language;
neither language has unique capabilities, just some things that it
does better than the other - but why re-write when C++ provides the
tools needed to link them together without a rewrite?
I think I have avoided confusing my biases with facts here :-)
CBFalconer wrote:
>
I concede my posts have not been accurate. I still don't think C
calling C++ is convenient, accurate, and really useful, although
possible. In the above:
Accurate?
My most common use for C calling C++ is C++ device drivers. The
interface between the operating system and drivers is a often a struct
of function pointers. I use extern "C" linkage functions as the public
interface for my drivers to populate these tables.
Calls between languages don't have to be direct. For a driver writer,
calling through function pointers is both convenient and really useful.
--
Ian Collins
CBFalconer wrote:
James Kuyper wrote:
>CBFalconer wrote: Various incorrect things.
... snip ...
>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 concede my posts have not been accurate. I still don't think C
calling C++ is convenient, accurate, and really useful, although
possible. In the above:
It's sometimes inconvenient, since you lose certain benefits of C++ and
have to add some extra syntactic sugar when you make a function callable
from C. However, it is quite certainly "accurate" and "useful".
I've worked with several libraries that used C++ internally and provided
both a C interface and a C++ interface; the C interface was simply a
bunch of wrapper functions that manipulated the C++ interface, which a C
program couldn't see (because it used classes).
foobar.h sets up definitions of foo and bar that requires them to
be called without name adornment The actual code is implemented in
the C++ file (.cpp would be more descriptive than .C, IMO).
..cpp or .cc is the usual convention when there's any possibility of
confusion. The .C convention doesn't work on systems that aren't
case-sensitive (e.g. Windows).
I guess the compiler can generate two references to foo, one adorned,
and one not adorned, although that is an unnecessary complication.
That's not required.
The C compiler processing foo.c will see a normal C function named
foo(), and it will generate the object code as it always does.
The C++ compiler processing main.C will see an extern "C" function named
foo(), and any time that C++ code calls it, it will call the unmangled C
name instead of the default mangled C++ name.
Since the C++ code is calling the unmangled name foo(), and the C
compiler produced a function named foo(), everything works.
Some confusion: Note that the code for bar is compiled with a C++
compiler. Thus it must follow C++ rules, for such things as
reserved names, size of char constants, etc. It can thus make a
great difference if bar is moved to a .c file, #includes
"foobar.h", and totally removed from main.C. To me, this is a
cleaner organization, and ensures that C code is compiled as C, and
C++ code is compiled as C++. Conceded, it will prevent using
std::cout etc.
bar() and baz() are both C++ functions, and are properly compiled with a
C++ compiler. bar() is callable from C, due to the way it's declared,
but baz() is not. However, bar() can call baz(), which makes bar() a
"wrapper" function for baz().
The wrapper is unnecessary in this case (baz() could have been extern
"C" and called directly from foo(), since its declaration doesn't
require any special C++ features), but it's a useful technique at times.
S
Stephen Sprunk wrote:
....
bar() and baz() are both C++ functions, and are properly compiled with a
C++ compiler. bar() is callable from C, due to the way it's declared,
but baz() is not. However, bar() can call baz(), which makes bar() a
"wrapper" function for baz().
The wrapper is unnecessary in this case (baz() could have been extern
"C" and called directly from foo(), since its declaration doesn't
require any special C++ features), but it's a useful technique at times.
In a more complicated version I've been thinking of, just to demonstrate
what's possible using this approach, the equivalent of baz() would be a
C++ function that uses many C++-specific features as part of the
function interface (it's a templated operator() overload with a default
argument that is a class member function), making it impossible to
declare it as extern "C".
The point is that the function interface (return type and parameter
list) of bar() can only use features that are shared between C and C++,
but the body of bar() has no such restrictions, and can include calls to
functions that are not subject to that same restriction. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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...
|
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:...
|
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...
|
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
|
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...
| |
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)
|
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...
|
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...
|
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...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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...
|
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...
|
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...
|
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
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...
| |