473,795 Members | 3,333 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A concern about mixing C and C++

Hello all,

I have a question and am seeking for some advice.

I am currently working to implement an algorithmic library. Because
the performance is the most important factor in later applications, I
decide to write it in C instead of C++. However, I thought it might be
convenient to use some C++ code at some misc places. I'm aware that, I
could always use the C++ compiler to get it work.

My concerns are:

1) Would the way I mix C and C++ code have any potential drawbacks to
the performance?
2) Would the way I mix C and C++ code have any potential drawbacks for
the future users to use the library?

My intention for choosing C interface instead of C++ OOD is to gain the
maximum performance as possible, yet I still like to use some C++
coding features (e.g., "const", reference instead of pointers, ...).

Thanks,

Gary

Jul 29 '06
28 3106
Keith Thompson a écrit :
Richard Heathfield <in*****@invali d.invalidwrites :
>>jacob navia said:

>>>There may be situations
where C++ templates outperform assembly language,

Jacob's talking through his hat again. His claim is easily disproved. All we
have to do is tell the compiler to generate assembly language from the C++
template code. We now have assembly language that performs exactly as well
as the C++ template code. And, given an experienced assembly language
programmer (to match the experienced C++ programmer who produces such
astoundingl y quick code), we can almost certainly find an optimisation,
however trivial, that will make the assembly language version at least a
little faster than the C++ template version from which it was generated.


On the other hand, for any language at a higher level than assembler,
the compiler may find opportunities for optimizations that someone
creating hand-written assembler wouldn't find, or would choose not to
use.

For example, if I'm writing low-level code that I expect to be
maintained, I'm not likely to perform a pervasive optimization that
works only if an array size is a power of 2.

A skilled assembly language programmer is likely to be much smarter
than an optimizing compiler, but an optimizer has a different set of
tradeoffs to consider. A programmer will perform optimizations over
time as he's working on a piece of code; an optimizing compiler will
redo all its work from scratch every time it's invoked.

Yes, you can use an optimizing compiler as a way to generate assembly
language -- but that argument doesn't apply to hand-written assembly
language.
The things I had in mind is that templates expose to the
compiler details that allows more optimizations than what
an assembly language programmer would do. Specifically it would
be highly surprising that he/she writes the same optimized version
for a qsort search for each possible type of argument that the
function could receive. Most likely it will design a general
qsort interface (like C offers) that will be highly optimized
but never as optimized as a specially tailored qsort for each
input type.

jacob
Jul 30 '06 #21
Ark
Ian Collins wrote:
Ark wrote:
>Ian Collins wrote:
>>Ark wrote:

Ian Collins wrote:

C++ gives the developer a choice between the C way of doing something
and the C++ way.
>
Ehmmm... please help me here: I am not a C++ guy.
AFAIK, C++ does not allow all the C way (example: tentative
declarations ).
Then, if I write C-style in C++, at the very minimum the C++ compiler
doesn't know e.g. about any exceptions that may be thrown in a function
I call and which is in a different translation unit. So it just has to
bring in the heavy machinery in just in case. Am I missing something?

If my understanding of tentative declarations is correct, they are
synonymous with forward declarations in C++ due to the differing use of
'struct' in a declaration, that is:

struct X;

forward declares the type X.

The compiler doesn't have to bother with unexpected exceptions when
compiling idiomatic C code, any unhandled exception can be caught by
whatever calls main().

As a trivial example, on my platform the following generated essentially
the same code when compiled as C or C++:

extern int fn(void);
extern void fn1(int);

typedef struct { int n; } X;

int main(void)
{
X x;

x.n = fn();

fn1( x.n );
}
1. Tentative declarations of variables are (in C) indistinguishab le from
definitions until the end of the translation unit; they AFAIK expressly
prohibited in C++. E.g., a (const) circular data structure like
typedef struct X {int x, const struct X *next} X;

typedef struct X {int x; const struct X *next;} X;

Is valid C but not C++.

typedef struct X {int x; const X *next;} X;

Is valid C++ but not C.

typedef struct X_t {int x; const struct X_t *next;} X;

Is valid C++ and C.
>const X x;
const X y;
const X z = {5, &x};
const X y = {6, &z};
const X x = {7, &y};
is a valid C but not C++.

Correct , C++ prohibits uninitialised consts. Easily fixed for both thus:

extern const X x;
extern const X y;
const X z = {5, &x};
const X y = {6, &z};
const X x = {7, &y};
>2. Interesting example; just curious what the differences are and
whether it matters that your function is called main, not, say, foo.

The C++ compiler pushed one extra register on the stack. The function
name does not make any difference.
1. It is not an easy fix if I want x, y, z to also be static. (Actually,
regardless of whether they are const).
2. It's interesting to understand /why/ C++ uses more stack. Is it, by
any chance, for passing (e.g. passing through) a pointer to an exception
object? In any event, those things get compounded... definitely a
consideration for resource-constrained environments...
- Ark
Jul 30 '06 #22

"jacob navia" <ja***@jacob.re mcomp.frwrote in message
news:44******** *************@n ews.orange.fr.. .
Keith Thompson a écrit :
>Richard Heathfield <in*****@invali d.invalidwrites :
>>>jacob navia said:
There may be situations
where C++ templates outperform assembly language,

Jacob's talking through his hat again. His claim is easily disproved. All
we have to do is tell the compiler to generate assembly language from the
C++ template code. We now have assembly language that performs exactly as
well as the C++ template code. And, given an experienced assembly
language programmer (to match the experienced C++ programmer who produces
such astoundingly quick code), we can almost certainly find an
optimisation , however trivial, that will make the assembly language
version at least a little faster than the C++ template version from which
it was generated.


On the other hand, for any language at a higher level than assembler,
the compiler may find opportunities for optimizations that someone
creating hand-written assembler wouldn't find, or would choose not to
use.

For example, if I'm writing low-level code that I expect to be
maintained, I'm not likely to perform a pervasive optimization that
works only if an array size is a power of 2.

A skilled assembly language programmer is likely to be much smarter
than an optimizing compiler, but an optimizer has a different set of
tradeoffs to consider. A programmer will perform optimizations over
time as he's working on a piece of code; an optimizing compiler will
redo all its work from scratch every time it's invoked.

Yes, you can use an optimizing compiler as a way to generate assembly
language -- but that argument doesn't apply to hand-written assembly
language.

The things I had in mind is that templates expose to the
compiler details that allows more optimizations than what
an assembly language programmer would do. Specifically it would
be highly surprising that he/she writes the same optimized version
for a qsort search for each possible type of argument that the
function could receive. Most likely it will design a general
qsort interface (like C offers) that will be highly optimized
but never as optimized as a specially tailored qsort for each
input type.
I did see some benchmarks for the standard template library, and they were
better than C equivalents. I thought that maybe the time had come to go to
C++.
What I forgot was that the syntax was difficult, and in fact a step too far,
with an already difficult and overloaded language. No one could use the STL
constructs effectively. So the experiment was short-lived, and now I have
virtually given up on C++ altogether.
--
www.personal.leeds.ac.uk/~bgy1mm
freeware games to download.
Jul 30 '06 #23
"ziman137" <ga********@yah oo.comwrote in message
news:11******** *************@m 73g2000cwd.goog legroups.com...
I am currently working to implement an algorithmic library. Because
the performance is the most important factor in later applications,
I
decide to write it in C instead of C++. However, I thought it might
be
convenient to use some C++ code at some misc places. I'm aware
that, I could always use the C++ compiler to get it work.
There's two basic approaches to mixing C and C++:

1. Write the code in C and provide (optional) C++ wrappers.
2. Write the code in C++ and provide (optional) C wrappers.

Once you use _any_ C++isms in your library, you're forever chained to
the portability problems that C++ still encounters, limit yourself to
systems with C++ available, etc. Once you've paid that price, you
might as well write the whole library in C++ and then it's off-topic
for clc (though clc++ will probably be happy to help with the C
wrappers).
My intention for choosing C interface instead of C++ OOD is to gain
the
maximum performance as possible, yet I still like to use some C++
coding features (e.g., "const", reference instead of pointers, ...).
If you're going to write the library in the subset of C++ that looks
like C, you might as well write it in C and forgo the syntactic sugar
that C++ provides (except, perhaps, in some C++ wrappers). If you
can't give up C++'s syntactic sugar, then write the library in _real_
C++ (not some ugly common subset of the two) and provide C wrappers.

Mixing languages in the same project is considered bad form unless you
have a really strong reason, and "const" or "references " are IMHO not
a reason worth dealing with all the headaches of that "solution".

S

--
Stephen Sprunk "God does not play dice." --Albert Einstein
CCIE #3723 "God is an inveterate gambler, and He throws the
K5SSS dice at every possible opportunity." --Stephen Hawking

--
Posted via a free Usenet account from http://www.teranews.com

Jul 30 '06 #24
On Sun, 30 Jul 2006 10:42:21 +1200, Ian Collins <ia******@hotma il.com>
wrote:
>Richard Heathfield wrote:
>Keith Thompson said:

<snip>
>>>On the other hand, for any language at a higher level than assembler,
the compiler may find opportunities for optimizations that someone
creating hand-written assembler wouldn't find, or would choose not to
use.


Sure, but perhaps you missed my point, which is that the /starting point/
for the assembly language programmer would be the super-efficient C++
template code, expressed in assembly language form. Given that starting
base, (a) it's bound to be as fast as the C++ template code, because it's
the same code that the C++ template code is compiled to - which is in
itself sufficient to destroy Mr Navia's point, and (b) it would be quite
surprising if the skilled assembly language programmer couldn't find /one/
hand-optimisation to make the asm form just a tiny smidgenette faster.
I don't know if you do this, but I often find I can obtain more
productive optimisations by using the generated assembly language to
tune the high level language code rather than hand editing the assembly.
When you do that, are you not tuning your code to a particular
compiler? No worse than tuning the assembler code, of course, and less
detrimental to portability. For the ultimate in (non-portable)
efficiency, you might do another iteration of the process.
>
One area optimising compilers have an edge and will continue to improve
is global optimisations, there is only so much code a human can retain
in working memory. We can often do better with micro-optimisations, but
the compiler is better equipped to see the big picture.
Even if the programmer can see the big picture, the compiler can do it
systematically and much more quickly.

--
Al Balmer
Sun City, AZ
Jul 31 '06 #25
Al Balmer wrote:
On Sun, 30 Jul 2006 10:42:21 +1200, Ian Collins <ia******@hotma il.com>
wrote:

>>Richard Heathfield wrote:
>>>Keith Thompson said:

<snip>

On the other hand, for any language at a higher level than assembler,
the compiler may find opportunities for optimizations that someone
creating hand-written assembler wouldn't find, or would choose not to
use.
Sure, but perhaps you missed my point, which is that the /starting point/
for the assembly language programmer would be the super-efficient C++
template code, expressed in assembly language form. Given that starting
base, (a) it's bound to be as fast as the C++ template code, because it's
the same code that the C++ template code is compiled to - which is in
itself sufficient to destroy Mr Navia's point, and (b) it would be quite
surprising if the skilled assembly language programmer couldn't find /one/
hand-optimisation to make the asm form just a tiny smidgenette faster.

I don't know if you do this, but I often find I can obtain more
productive optimisations by using the generated assembly language to
tune the high level language code rather than hand editing the assembly.


When you do that, are you not tuning your code to a particular
compiler? No worse than tuning the assembler code, of course, and less
detrimental to portability. For the ultimate in (non-portable)
efficiency, you might do another iteration of the process.
Like most low level optimisations, I tend to do this on embedded
systems, where portability isn't too much of an issue (I've found it
more cost effective to throw faster hardware at desktop applications
rather than fiddle with low level optimisations). The results can be
dramatic, one compiler I used generated diabolical code with loops like

for( i = 0; i < size; ++i )
{
doStuffWith( array[i] );
}

But good tight code with

int* p = array;
int* end = array+size;

while( p != end )
{
doStuffWith( *p++ );
}

--
Ian Collins.
Jul 31 '06 #26
On Mon, 31 Jul 2006 19:21:07 +1200, Ian Collins <ia******@hotma il.com>
wrote:
>Like most low level optimisations, I tend to do this on embedded
systems, where portability isn't too much of an issue (I've found it
more cost effective to throw faster hardware at desktop applications
rather than fiddle with low level optimisations). The results can be
dramatic, one compiler I used generated diabolical code with loops like

for( i = 0; i < size; ++i )
{
doStuffWith( array[i] );
}

But good tight code with

int* p = array;
int* end = array+size;

while( p != end )
{
doStuffWith( *p++ );
}
I can believe it - I've seen some strange things. Sometimes compilers
used for embedded devices seem to assume that the user will tweak the
assembler :-)

I don't do much embedded programming myself anymore, but the hardware
guy down the hall yells for help quite often, so I still see a lot of
it. We often sit in his office and massage C source until the
assembler looks the way he wants it.

--
Al Balmer
Sun City, AZ
Jul 31 '06 #27
Ian Collins posted:
One compiler I used generated diabolical code with loops like

for( i = 0; i < size; ++i )
{
doStuffWith( array[i] );
}

But good tight code with

int* p = array;
int* end = array+size;

while( p != end )
{
doStuffWith( *p++ );
}

If I know the the loop must execute at least once, then I choose:

T *p = array;

T const *const p_over = array + len;

do Process(*p++);
while(p_over != p);

--

Frederick Gotham
Jul 31 '06 #28
On Sun, 30 Jul 2006 17:07:12 +1200, Ian Collins <ia******@hotma il.com>
wrote:
Ark wrote:
1. Tentative declarations of variables are (in C) indistinguishab le from
definitions until the end of the translation unit; they AFAIK expressly
prohibited in C++. E.g., a (const) circular data structure like
typedef struct X {int x, const struct X *next} X;

typedef struct X {int x; const struct X *next;} X;

Is valid C but not C++.
Wrong. In C++ it is a 'benign' redefinition of the typename, which is
allowed. For essentially this reason.
typedef struct X {int x; const X *next;} X;

Is valid C++ but not C.

typedef struct X_t {int x; const struct X_t *next;} X;

Is valid C++ and C.
Both right.
const X x;
const X y;
const X z = {5, &x};
const X y = {6, &z};
const X x = {7, &y};
is a valid C but not C++.

Correct , C++ prohibits uninitialised consts. Easily fixed for both thus:
Even for nonconst C++ prohibits the declare-now define-later approach
without (explicit) extern, which as you note fixes the problem.
extern const X x;
extern const X y;
const X z = {5, &x};
const X y = {6, &z};
const X x = {7, &y};
However, this does not work for static=internal-linkage variables.
C++ does not allow /*qual?*/ static X x;
then /*qual*/ /*static*/ X x = init;

Or, write a ctor or other factory routine for X and:
const X z = X /* or makeX */ (5, &x);
etc.

For this particular case in EITHER C or C++
I might also consider something like:
const /*struct*/ X array [3] =
{ { 5, &array[2] }, { 6, &array[1] }, { 7, &array[0] } };
#define x array[2] // only if x is a more unique name
or in C++ X & x (&array[2])
etc.

- David.Thompson1 at worldnet.att.ne t
Aug 14 '06 #29

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

Similar topics

3
3491
by: bergel | last post by:
Hello, Does anyone already have some experience in mixing AWT and Swing? Is it conceptually doable? Does the design of Swing prevent interaction between an AWT and a Swing widget? Regards, Alexandre
6
4910
by: Russell E. Owen | last post by:
At one time, mixing for x in file and readline was dangerous. For example: for line in file: # read some lines from a file, then break nextline = readline() # bad would not do what a naive user might expect because the file iterator buffered data and readline did not read from that buffer. Hence the call to readline might unexpectedly skip some lines.
0
1830
by: Erik Max Francis | last post by:
Is there any prohibition against mixing different protocols within the same pickle? I don't see anything about this in the Python Library Reference and, after all, the pickle.dump function takes a protocol argument for each time it's called. (This is in Python 2.3.3.) I have a pickle containing two objects: a tag string and a (large) object containing many children. The identifying string is there so that you can unpickle it and...
4
23692
by: Rudolf | last post by:
Is it possible to add a vb.net source code module to a c# project and if so how? Thanks Rudolf
1
3421
by: Marc Cromme | last post by:
I would like to ask a question about (good ?) style and possibilities in mixing C FILE* and C++ file streams. The background is that I want to use the C libpng library from within C++, but I would like to open C++ file streams due to easier exception handeling and safe closure of file ressources. Question 1: I open a standard file stream and want to transfer some binary read bits
4
1938
by: Cristian Tota | last post by:
Hi, I'd appreciate any thoughts on mixing C++ and C code. I have a project that uses a given C interface, the rest of the project can be either in C or C++. What would be the recomended design pattern in this case? C++ allows for a better design, but integrating the code with the C code isn't straight forward, it becomes rather messy. Code readability and maintenance are important, since the project will grow in the future. Maybe someone...
49
5909
by: Neil Zanella | last post by:
Hello, Often I happen to be dealing with nonnegative integers and since I know I won't need negative numbers here I declare them as unsigned simply to make the program somewhat clearer. Effectively, though, signed integers would often work too since unless I am doing some modular arithmetic modulo the word length then I almost never need to use the high bit since the integers I deal with are usually not that large, and I would assume...
2
2420
by: Dan | last post by:
Hi What are the dangers of mixing asp and asp.net? For the .net part of the site i will need to use the global.asax file but for the asp parts it will be using the other global. file, is there anyway to get to both use the same one? For example i want to convert my homepage to aspx first, but in doing so my session var that needs to be initialised wont be as it will use the global.asax and not the global.asa.
6
301
by: ziman137 | last post by:
Hello all, I have a question and am seeking for some advice. I am currently working to implement an algorithmic library. Because the performance is the most important factor in later applications, I decide to write it in C instead of C++. However, I thought it might be convenient to use some C++ code at some misc places. I'm aware that, I could always use the C++ compiler to get it work.
0
9519
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,...
0
10436
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...
0
10213
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10163
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
10000
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
9040
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...
0
6780
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
5436
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...
2
3722
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.