Archived

This topic is now archived and is closed to further replies.

How to code C in a C++ program?

Recommended Posts

As I am learning more about C++, and I have been seeing C code is much faster then C++ code in most things. How would I opt say the Drawing routines in C while having an OOP program. So in other words how would I code in C in a C++ source file? Or would I just write my functions in C and include the source files and call the functions from the C++ source file? Or do I call the C headers and write my code that way inthe C++ source file? Thank you.

Share on other sites
quote:
Original post by Dalik
As I am learning more about C++, and I have been seeing C code is much faster then C++ code in most things.
Could you please show us what code that might be?
quote:
How would I opt say the Drawing routines in C while having an OOP program.
Drawing routines are in most (if not all) cases identical in C and C++
quote:
So in other words how would I code in C in a C++ source file?
Take a guess
quote:
Or would I just write my functions in C and include the source files and call the functions from the C++ source file? Or do I call the C headers and write my code that way inthe C++ source file?
That does not make sense to me.

Where do these concerns of your''s come from? Some "features" of C++ may make a program less efficient than a C program, because you don''t use these features in C. When it boils down to graphics, about the only thing to stay away from is virtual functions inside tight loops.

Share on other sites
quote:

and I have been seeing C code is much faster then C++ code in most things

Sorry to disappoint you, but you have seen wrong. The speed is not in the language, but in how you use it. If you can''t write fast enough code in C++, then you can''t write fast enough code in C either.

Share on other sites
I have to make this kinda fast but if you have CODE COMPELTE (a book)there are many many examples of benchies where C code is faster then C++ code. optimized of course and even unoptimized.

This was a waste of your time, since my concern wasnt which one is faster. I was asking how do you write C code in a C++ program. Or I could have asked how do you write C code in a pascal suorce? Or Ada in a java program. I know you can write C++ struct code and thats fine but again your using C++ headers and if your using C++ headers your using C++ code. So in other words would you just include C headers and you would get C code? Am I thinking right? Of do I have to write the code ina seperate source file and include the functions in the C++ program?

Thank you.

Share on other sites
It''s not so much that C++ is slower than C, it''s more that object oriented is slower than procedural (and that includes using objects like file streams over the C methods). Although it''s usually almost as fast, except maybe on embedded systems (where speed really matters).

Overall if you are just learning C++ you are probably not programming anything that requires a lot of speed. Even if you used pure C/procedural, you probably wouldn''t notice an increase anyway.

Share on other sites
You''re asking this like they are 2 completely unrelated languages. Since C++ is a subset of C you can use them together with little or no problems. For example I prefer C style file i/o (FILE, fopen, etc) so in my classes that read/write to files use the C file i/o methods/structures.

Here''s a simple generic example:

#include <stdio.h>
#include <string>
using std::string;

class CPlayer
{
private:
FILE *fData;
int iStrength;
string sFilename;
public:
CPlayer();
~CPlayer();
void CreateGeneric(const char *filename);
};

void CPlayer::CreateGeneric(const char *filename)
{
iStrength=100;
sFilename=filename;
fData=fopen(sFilename.c_str(),"wb");
fwrite((void *)&iStrength,sizeof(int),1,fData);
fflush(fData);
fclose(fData);
}

Perfectly legal mix of C and C++ in a *.cpp file.

MSVC++ 6
DirectX 7

Share on other sites
quote:
Original post by Dalik
I have to make this kinda fast but if you have CODE COMPELTE (a book)there are many many examples of benchies where C code is faster then C++ code. optimized of course and even unoptimized.

That book was written over 10 years ago. C++ compiler technology has advanced a lot in that time.

"If there is a God, he is a malign thug."
-- Mark Twain

Share on other sites
Well if you write C-legal code and functions in your C++ project, then it is my understanding that today''s C++ compilers will usually generate code that is as efficient as C-only compilers would generate, or at least so close as to be trivial.

If you''re not convinced that is the case, you could generate libraries using a C compiler and then link them into your C++ project.

Maybe the extern "C" declaration would make a performance difference too, but I kinda doubt it.

Value of good ideas: 10 cents per dozen.
Implementation of the good ideas: Priceless.

Proxima Rebellion - A 3D action sim with a hint of strategy

Share on other sites
Any C statement is also a legal C++ statement, so just compile everything with a C++ compiler and it should work out fine. Writing C code in a C++ program is not at all the same as writing C code in a pascal program. I think you're a little confused as to what C++ is. It's just C with some additional functionality. Also, it won't necessarily speed up your program. The main determining factor of your program's speed is the algorithms you use. I believe, and if someone has evidence to the contrary, let me know, that if you write a program in C and compile it with a C compiler, your machine code would be almost identical to the code produced by a C++ compiler. They didn't take out optimization techniques in C++ compilers that are present in C compilers.

[edited by - kdogg on March 16, 2003 2:32:03 PM]

Share on other sites
quote:
Dalik
As I am learning more about C++, and I have been seeing C code is much faster then C++ code in most things.

No.

quote:
Original post by kdogg
Any C statement is also a legal C++ statement

No.

  /* foo.h */#ifdef cplusplusextern "C"{#endifint my_c_function();#ifdef cplusplus}#endif

  /* foo.c */#include "foo.h"int my_c_function(){  return 0;}

  /* bar.cpp */#include "foo.h"// When you mix C and C++, main() MUST be in a C++ fileint main() {  return my_c_function();}

Anyway, since you''re likely to be using a combined C/C++ compiler, don''t expect the code compiled as C to outperform the code compiled as C++.

[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share on other sites
quote:
Original post by jdinger2
You''re asking this like they are 2 completely unrelated languages. Since C++ is a subset of C...

You mean "superset"

Share on other sites
So tell me if I am wrong.

I write 3 programs, program A is done in C using a C only compiler, program B is done in C++ struct code, program C is done using C++ OOP code.

What program will be faster, by performing I/O functions 1000 times, so read and write to a file also nothing is optimized.

I think program A(in C) will be the fastest.

When I said "I have been seeing C code is much faster then C++ code in most things" I was refering to posts I have seen on this board. I know C is faster then C++ even if its a little its STILL faster, using the same algorithm and such, pure C is faster. Another example, why are major OS''s programmed in C, maybe because they hate OOP or to make there project harder to make?

If C++ is the "same speed" as a C program then why do most programmers program in C for time/speed critical apps compared to C++ or java?

Yes Code Complete is about 10 years old, but again his benchies prove that C is faster in nearly all operations even compared to other languages, such as Ada, and pascal and others.

Now since this post went off topic. I think someone said in general just to include the header files that you want to use the C version, so if this is correct then I was right, and for the other part of the question, you write your C code in the C++ source file and thats it.

Gaining performance is done a few ways, the algorithm, and making small optimzing improvments through out your code. Gaining speed isnt done in one place in your code its a little bit all over the place.

Now I hope this thread can end, just to be clear I like both languages.

Share on other sites
To give a straight up answer:

In MSVC, at least, when creating a new C++ Source File, simply specify the filename as "somefile.c" instead of "somefile" or "somefile.cpp". This will force the compiler to use pure C compilation on the file. It will also turn off definition of CPLUSPLUS.

Share on other sites
quote:
Original post by Dalik
So tell me if I am wrong.

I write 3 programs, program A is done in C using a C only compiler, program B is done in C++ struct code, program C is done using C++ OOP code.

What program will be faster, by performing I/O functions 1000 times, so read and write to a file also nothing is optimized.

I think program A(in C) will be the fastest.

Tell you what. You write that C program reading in an ASCII text file 1000 times, and I''ll use C++ to read in a binary file 1000 times, and we''ll see which is faster.

quote:

When I said "I have been seeing C code is much faster then C++ code in most things" I was refering to posts I have seen on this board. I know C is faster then C++ even if its a little its STILL faster, using the same algorithm and such, pure C is faster. Another example, why are major OS''s programmed in C, maybe because they hate OOP or to make there project harder to make?

http://www.gnu.org/software/hurd/hurd.html

quote:

Unlike other popular kernel software, the Hurd has an object-oriented structure that allows it to evolve without compromising its design. This structure will help the Hurd undergo major redesign and modifications without having to be entirely rewritten.

quote:

If C++ is the "same speed" as a C program then why do most programmers program in C for time/speed critical apps compared to C++ or java?

do they? Last I checked, Game programming in both C++ and Java is alive and kicking.

quote:

Yes Code Complete is about 10 years old, but again his benchies prove that C is faster in nearly all operations even compared to other languages, such as Ada, and pascal and others.

Those are on old compilers. You''ve already been told this. I suspect that you don''t know enough about compiles, and possibly programming in general, to undestand what they''re saying.

quote:

Gaining performance is done a few ways, the algorithm, and making small optimzing improvments through out your code. Gaining speed isnt done in one place in your code its a little bit all over the place.

I could be mistaken, but I believe generally you try to optimize the bottleneck, not every single thing in your code. I''m not an experienced games programmer so I can''t say for sure. Perhaps someone else can enlighten us?

--------------------------------------

2 things:

1)
My advice to you is to quit using C or C++ and use straight assembly. You seem to be extremely worried about speed, and we all know that assembly is the fastest you''re going to get.

2)
You''ve obviosly been speaking to someone with a bias, or have simply decided to be someone with a bias. You hear it all the time, C is more l337 than C++ because it''ll run circles around it. That''s as tiring as the Java nutz who run around claiming Java''s going to take over the world...

As a matter of fact, there''s a website that created a C program, and a C++ program that do the exact same thing. In most cases C++ beat the C program. The reason is because if you emulate the OOP of C++, you lose speed, even in C.

This has already been mentioned, but I''ll repeat it. It''s not the language, it''s the paradigm. The sooner you understand that, you better off you''ll be.

Share on other sites
The above post was mine. I mistakenly thought I was logged in.

[edited by - Recondite Phreak on March 17, 2003 1:48:37 AM]

Share on other sites

you''re killing me with your stupidity, could you possibly
just shutup.

Thank You.

Share on other sites
its true that compilers have come a long way since 10yrs ago. in fact, it may appear compiler code may come close to the best assembly code out there at present. The real idea is indeed in optimizing the algorithms instead.

also, comparing an iteration based analysis; say 10000 times of test A vs B; is not a very good way to gauge real world performance. I remember posting in another thread pertaining timers. One timer is 4 times slower than another per call, and it stacks up in performance loss over iterative comparison.

however, in a real world application, such an object gets called once per frame, probably accounting for a completely insignificant determinant in application performance. as complexity of application increases, the performance loss incurred completely disregard petty stuff as these small ''things''. wat will matter are the critical segments of the and the algorithms used in the program.

dun bother comparing the language. its different if its between java and c/c++ because thats comparing a bytecode-translation to pure machine code. but c is a subset of C++ and recent compilers dun seem to differentiate the two by much.

the only issue in performance comes in integrated devices where space AND speed is critical. object oriented overhead MAY take more memory and storage, plus the additional level of indirection existent in inheritances could be an issue. but under allother circumstances this issue is not really an issue

Share on other sites
On Topic
I don''t believe you understand, completely, what you''re asking when you say How do I "code C in a C++ program".

From the C++ FAQ-Lite
Mixing C and C++

I''d advise you to pay particular attention to the following:

quote:

BTW there is another way to handle this whole thing: compile all your code (even your C-style code) using a C++ compiler. That pretty much eliminates the need to mix C and C++, plus it will cause you to be more careful (and possibly ?hopefully!? discover some bugs) in your C-style code. The down-side is that you''ll need to update your C-style code in certain ways, basically because the C++ compiler is more careful/picky than your C compiler. The point is that the effort required to clean up your C-style code may be less than the effort required to mix C and C++, and as a bonus you get cleaned up C-style code.

Off Topic
Today, the same code compiled as C is not going to run any faster than if compiled as C++. Reading one (dated) book does not make you an expert, particularly a book who''s objective isn''t even related to C, C++, or any other programming language; It''s about software engineering and its conventions. Read it for what it''s worth.

Share on other sites
""If C++ is the "same speed" as a C program then why do most programmers program in C for time/speed critical apps compared to C++ or java?""

"do they? Last I checked, Game programming in both C++ and Java is alive and kicking."

I was thinking more along the lines of none game related programs. Sorry for the mistake

""Gaining performance is done a few ways, the algorithm, and making small optimzing improvments through out your code. Gaining speed isnt done in one place in your code its a little bit all over the place.

" could be mistaken, but I believe generally you try to optimize the bottleneck, not every single thing in your code. I''m not an experienced games programmer so I can''t say for sure. Perhaps someone else can enlighten us?"

You optimize the code that is slowing down your program, which could be more then a few places. This could mean you have 100 places where your code can be optimzed to give you another 2 sec reduction loading a level, and another 22fps for the game, AI acts faster.. That all I was saying.

No I am not an awsome programmer and no I dont read about compiler design. I do know the performace difference isnt a lot on todays computers, to the point where you can notice it if at all. I picked Code Complete because it was the only book I read that showed benchies. I am still learning like everyone else. I will be confused about something and others I will have my mind set and if I am wrong then I will either find that out on my own or just change my mind from being told different. From reading the forums not everyone is pro C++ and not everyone is pro C. Which is normal defend what you believe in. There are pros and cons to each language and everyone should be clear on what they can and cant do well. I get alot of what I know from this board, I dont believe in everything I see but some of it I do. I am taking this as a good learning experience. I do have one question that wasnt answered.

Why are all the important OS''s(windows, unix/linux, I was say MAC so this doesnt start another war) programmed in C then C++ or even other languages?

Share on other sites
quote:
Original post by Dalik
Why are all the important OS''s(windows, unix/linux, I was say MAC so this doesnt start another war) programmed in C then C++ or even other languages?

You added the adjective important in hopes that it would exclude the CNU/Hurd, but it most certainly doesn''t.

In case you don''t know, FSF(Free Software Foundation) was founded by Richard Stallman. He had created an OS using a bunch of different tools, but was missing a kernel. This is where Linux came in. With Linux, the OS was complete. However, it''s not exactly the vision that Stallman had in mind, so he''s developing the Hurd to be the eventual replacement for Linux in the FSF. This is why there''s a big debate over calling it Linux or calling it GNU/Linux, since most of the system is GNU software. The Hurd is very relevant, and is written using OOP.

Unix was originally ported to C for portability. C was made to be platfrom independant. This was before C++.

Minix was made to be a learning tool, and was written in C. Linus Torvalds created Linux based off of Minux(originally).

I''m not sure, but I''m assuming the original DOS was in C, therefore everything else naturally extended off of it.

But it doesn''t really matter because OS programming is not Game Programming, and your correlation between the two is flawed.

You also need to realize that speed is not the only determining factor when choosing a language for most applications. There''s also memory concerns, readability, scalability,etc. If speed/memory were the only factors, Java would never have become popular.

Share on other sites
dammit, I logged in. Opera must be doing something screwy *sigh*

Share on other sites
Quite simply, anyone who thinks C is faster than C++, and anyone who thinks C++ is identical to C, both need to learn more about their programming language.

An algorithm written in C is faster than it's equivelent C++ version, IF AND ONLY IF, the C++ compiler is including extra, unneeded, things in the object file. Vice-versa, a C++ program is IDENTICAL to a C program, IF AND ONLY IF, the compiler does not include any extra C++ niceties in the particular case in question.

Such things do exist, an are relevant in some cases, such as extra constructor and destructor function calls. If a programmer translates a program which uses only built in types (no classes or structs) to C++ (meaning the simply compile it under a C++ compiler) then it will perform the same (assuming equal levels of compiler enginuity. If a person translates a struct oriented C program to C++, it MAY perform better or worse, depending on the presence of extra initialization and cleanup code. Such code exists in MOST nieve C++ programs, because programmers do not pay enough attention to pre-post conditions, and end up performing unnecessary zeroing of data, and checking of correctness. But that type of code, is usally a programmer issue (non-optimized programming ideas), not a language issue.

[edited by - Xai on March 17, 2003 2:44:49 PM]

• Forum Statistics

• Total Topics
628357
• Total Posts
2982225

• 10
• 9
• 24
• 11
• 9