C 언어에 비해 C ++의 한계는 무엇입니까? [닫은]
C ++의 장점은 다음과 같습니다.
- C ++은 그들이 요구하는 특정 기능을 제공합니다
- C 컴파일러는 거의 확실히 C ++ 컴파일러이므로 소프트웨어 비용에 영향을주지 않습니다.
- C ++는 C만큼 이식성이 뛰어납니다
- C ++ 코드는 C만큼 효율적일 수 있습니다.
C ++ 대신 C ++를 사용해야하는 구체적인 이유와 특정 시나리오가 있습니까?
이 질문에 대한 참조 : C의 제네릭 라이브러리
이 질문은 언어 제한에 대해 묻는 것이기 때문에 한 언어를 다른 언어로 배우거나해서는 안되기 때문에 중복되지 않습니다.
Peter Kirkham의 게시물은 특히 내가 고려하지 않은 C99 문제와 관련하여 가장 유익한 정보였습니다. 참여한 다른 모든 분들께 감사드립니다.
이것은 C에 대한 제네릭 라이브러리에 대해 묻는 현재 질문에 대한 답변에 의해 프롬프트됩니다. 질문자는 구체적으로 C ++을 사용하고 싶지 않다고 말합니다.
C는 완전한 프로그래밍 언어입니다. C는 C ++의 임의의 하위 집합이 아닙니다. C는 전혀 C ++의 하위 집합이 아닙니다.
이것은 유효한 C입니다.
foo_t* foo = malloc ( sizeof(foo_t) );
C ++로 컴파일하려면 다음과 같이 작성해야합니다.
foo_t* foo = static_cast<foo_t*>( malloc ( sizeof(foo_t) ) );
더 이상 C가 유효하지 않습니다. (C 스타일 캐스트를 사용할 수 있습니다.이 경우 C로 컴파일되지만 대부분의 C ++ 코딩 표준과 많은 C 프로그래머가 피할 수 있습니다. " .
그것들은 같은 언어가 아니며 C에 기존 프로젝트가있는 경우 라이브러리를 사용하기 위해 다른 언어로 다시 작성하고 싶지 않습니다. 작업중인 언어로 인터페이스 할 수있는 라이브러리를 사용하는 것이 좋습니다. ( extern "C"C ++ 라이브러리의 템플릿 / 인라인 방식에 따라 몇 가지 래퍼 함수를 사용하여 가능할 수도 있습니다 .)
내가 작업중 인 프로젝트에서 첫 번째 C 파일을 가져 와서 다음과 같이 바꾸면 gcc std=c99됩니다 g++.
sandiego:$ g++ -g -O1 -pedantic -mfpmath=sse -DUSE_SSE2 -DUSE_XMM3 -I src/core -L /usr/lib -DARCH=elf64 -D_BSD_SOURCE -DPOSIX -D_ISOC99_SOURCE -D_POSIX_C_SOURCE=200112L -Wall -Wextra -Wwrite-strings -Wredundant-decls -Werror -Isrc src/core/kin_object.c -c -o obj/kin_object.o | wc -l
In file included from src/core/kin_object.c:22:
src/core/kin_object.h:791:28: error: anonymous variadic macros were introduced in C99
In file included from src/core/kin_object.c:26:
src/core/kin_log.h:42:42: error: anonymous variadic macros were introduced in C99
src/core/kin_log.h:94:29: error: anonymous variadic macros were introduced in C99
...
cc1plus: warnings being treated as errors
src/core/kin_object.c:101: error: ISO C++ does not support the ‘z’ printf length modifier
..
src/core/kin_object.c:160: error: invalid conversion from ‘void*’ to ‘kin_object_t*’
..
src/core/kin_object.c:227: error: unused parameter ‘restrict’
..
src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier
src/core/kin_object.c:271: error: ISO C++ does not support the ‘z’ printf length modifier
총 69 줄의 오류 중 4 개는 잘못된 변환이지만 대부분 C99에는 있지만 C ++에는없는 기능에 해당합니다.
그 기능을 재미있게 사용하는 것과는 다릅니다. 다른 언어로 이식하려면 상당한 노력이 필요합니다.
따라서 제안하는 것은 분명 잘못입니다
[a] C 컴파일러는 거의 확실하게 C ++ 컴파일러이므로 소프트웨어 비용에 영향을주지 않습니다.
기존 C 코드를 C ++의 절차 적 하위 집합으로 이식 할 때 종종 상당한 비용 영향이 있습니다.
따라서 C에서 대기열 의 라이브러리 구현을 찾는 질문에 대한 대답으로 'C ++ std :: queue 클래스 사용' 을 제안하는 것은 '객관적 C 사용'을 제안 하고 'JNI를 사용하여 Java java.util.Queue 클래스를 호출하십시오' 또는 'CPython 라이브러리 호출' -목표 C는 실제로 C의 적절한 상위 세트 (C99 포함)이며 Java 및 CPython 라이브러리는 관련이없는 코드를 C ++ 언어로 이식하지 않고도 C에서 직접 호출 할 수 있습니다.
물론 C ++ 라이브러리에 C façade를 제공 할 수는 있지만 일단 C ++을 수행하면 Java 또는 Python과 다르지 않습니다.
나는 그것이 전문가도 아니고 특정 좋은 대답이 아니라는 것을 알고 있지만, 실제로 C를 좋아하기 때문입니다. C는 작고 단순하며 두뇌에 모든 언어를 적용 할 수 있습니다 .C ++은 항상 거대한 혼란스러워 보입니다 모든 종류의 층으로 나는 힘든 시간을 보냅니다. 이로 인해 C ++을 작성할 때마다 C를 코딩 할 때보 다 디버깅 및 하드 표면에 대해 머리를 두드리는 데 더 많은 시간을 소비한다는 것을 알았습니다. 다시 말하지만 이것은 대부분 내 자신의 '무지'의 결과라는 것을 깨달았습니다.
내가 선택하면 파이썬 (또는 C #)의 인터페이스 및 데이터베이스 상호 작용과 같은 모든 고급 수준의 내용과 C에서 빠를 수있는 모든 내용을 작성하겠습니다. C ++로 모든 것을 작성하는 것은 모든 세계에서 최악을 얻는 것처럼 느껴집니다.
편집 : 몇 가지 C ++ 기능을 가진 C가 프로젝트에서 여러 사람이되거나 유지 관리가 우선 순위 인 경우 크게 나쁜 생각이라고 덧붙이고 싶습니다. '몇 가지'를 구성하는 요소와 C에서 수행해야하는 비트 및 C ++의 비트가 결국 정신 분열증을 유발하는 코드베이스로 이어지는 부분에 대해서는 의견이 분분합니다.
C ++은 저수준 임베디드 시스템과 같은 일부 실제 환경에서는 지원되지 않습니다. 그리고 그 이유는 다음과 같습니다. C는 그러한 것들에 대해 쉽게 충분합니다. 왜 더 큰 것을 사용합니까?
나는 C ++로 프로그래밍하는 것을 싫어한다.
몇 가지 이유는 다음과 같습니다.
- 지원 부족-모든 C 컴파일러가 C ++ 컴파일러 인 것은 아닙니다. C ++를 지원한다고 주장하더라도 모든 컴파일러가 표준을 특별히 준수하는 것은 아닙니다. 그리고 일부 C ++ 컴파일러는 절망적으로 부풀어지고 비효율적 인 코드를 생성합니다. 일부 컴파일러에는 표준 라이브러리의 끔찍한 구현이 있습니다. 커널 모드 개발에서는 일반적으로 C ++ 표준 라이브러리와 일부 언어 기능을 사용할 수 없습니다. 언어의 핵심을 고수하면 C ++ 코드를 작성할 수 있지만 C로 전환하는 것이 더 간단 할 수 있습니다.
- 정통. C ++는 복잡한 언어입니다. C ++보다 누군가에게 C를 가르치는 것이 더 쉽고, 좋은 C ++ 프로그래머보다 좋은 C 프로그래머를 찾는 것이 더 쉽습니다. (여기서 키워드는 "좋은"입니다. 많은 C ++ 프로그래머가 있지만 대부분 언어를 제대로 배우지 못했습니다)
- 학습 곡선-위와 같이 누군가에게 C ++를 가르치는 것은 큰 작업입니다. 미래에 다른 사람이 유지 관리 해야하는 앱을 작성하고 있으며 다른 사람들이 C ++ 프로그래머가 아닐 수 있다면 C로 작성하면 훨씬 쉽게 이해할 수 있습니다.
나는 그것을 피할 수있을 때 여전히 C ++로 작성하는 것을 선호하며 전반적으로 이점이 단점보다 중요하다고 생각합니다. 그러나 어떤 경우에는 C를 사용한다는 주장도 볼 수 있습니다.
임베디드 프로그래밍, 성능 및 물건에 대한 많은 논쟁이 있지만, 나는 그것을 사지 않습니다. C ++는 이러한 영역에서 C와 쉽게 비교됩니다. 하나:
최근 15 년 이상 C ++로 프로그래밍 한 후 C 루트를 다시 발견했습니다. C ++에는 인생을 편하게 해주는 좋은 기능이 있지만 함정과 많은 일을하는“항상 더 나은 길”도 있습니다. 당신은 실제로 당신이 한 솔루션에 대해 꽤 행복하지 않습니다. (나를 잘못하지 마라, 이것은 좋은 일이 될 수 있지만 대부분은 그렇지 않다).
C ++은 무한한 총성을냅니다. 어느 쪽이 좋을지 모르지만 어쨌든 항상 너무 많이 사용하게됩니다. 이것은 추상화, 일반성 등의 "좋은"및 "예쁜"레이어로 솔루션을 위장하고 있음을 의미합니다.
C로 돌아가는 것을 발견 한 것은 실제로 재미있는 프로그래밍 이었다는 것입니다. 상속을 가장 잘 사용하는 방법에 대해 모델링하고 생각하는 데 너무 많은 시간을 보냈으므로 C로 프로그래밍하면 실제로 소스 코드가 더 작고 읽기 쉽습니다. 이것은 물론 당신이 자기 훈련 수준에 따라 다릅니다. 그러나 직접 코드에 너무 많은 추상화를 적용하는 것은 매우 쉽지만 실제로는 절대 필요하지 않습니다.
C는 코드 조각을 볼 때 실제로 무슨 일이 일어나고 있는지 볼 수 있다는 주요 이점이 있습니다 (예 : 전 처리기 : -E로 컴파일 한 다음 볼 수 있습니다). C ++ 코드를 볼 때 너무 자주 사실이 아닙니다. 범위 또는 할당으로 인해 암시 적으로 호출되는 생성자와 소멸자가 있습니다. 잘못 잘못 사용되지 않아도 놀라운 동작을 할 수있는 연산자 오버로드가 있습니다. 나는 제어 괴물이라는 것을 인정하지만, 이것이 신뢰할 수있는 소프트웨어를 작성하려는 소프트웨어 개발자에게는 나쁜 습관이 아니라는 결론에 도달했습니다. 나는 단지 내 소프트웨어가해야 할 일을 정확하게 수행하고 동시에 위장에 나쁜 느낌이 들지 않는다고 말할 수있는 공정한 기회를 갖고 싶다.
C++ also has templates. I hate and love them, but if anyone says he or she fully understands them I call him/her a liar! That includes the compiler writers as well as the folks involved in defining the standard (which becomes obvious when you try to read it). There are so many absurdly misleading corner cases involved that it's simply not possible to consider them all while you write actual code. I love C++ templates for their sheer power. It's really amazing what you can do with them, but they can likewise lead to the strangest and hardest to find errors one can (not) imagine. And these errors actually happen and not even rarely. Reading about the rules involved to resolve templates in the C++ ARM almost makes my head explode. And it gives me the bad feeling of wasted time having to read compiler error messages that are several 1000 characters long for which I need already 10 minutes or more to understand what the compiler actually wants from me. In typical C++ (library) code you also often find a lot of code in header files to make certain templates possible which in turn makes compile/execute cycles painfully slow even on fast machines and requires recompilation of large parts of the code when you change something there.
C++ also has the const trap. You either avoid const for all but the most trivial use cases or you will sooner or later have to cast it away or to refactor large parts of the code base when it evolves, especially when you are about to develop a nice and flexible OO design.
C++ has stronger typing than C, which is great, but sometimes I feel like I'm feeding a Tamagotchi when I try to compile C++ code. A large part of the warnings and errors I usually get from it are not really me doing something that wouldn't work, but just things the compiler doesn't like me to do this way or not without casting or putting some extra keywords here and there.
These are just some of the reasons why I don't like C++ for software that I write alone only using some allegedly robust external libraries. The real horror begins when you write code in teams with other people. It almost doesn't matter whether they are very clever C++ hackers or naive beginners. Everybody makes errors, but C++ makes it deliberately hard to find them and even harder to spot them before they happen.
With C++ you are simply lost without using a debugger all the time but I like to be able to verify the correctness of my code in my head and not having to rely on a debugger to find my code running on paths I would never have anticipated. I actually try to run all my code in my head and try to take all the branches it has, even in subroutines etc. and to use a debugger only occasionally just to see how nicely it runs through all the cosy places I prepared for it. Writing and executing so many test cases that all code paths have been used in all combinations with all sorts of strange input data is simply impossible. So you might not know of the bugs in C++ programs but that doesn't mean they are not there. The larger a C++ projects gets the lower becomes my confidence that it will not have lots of undetected bugs even if it runs perfectly with all the test data we have at hand. Eventually I trash it and start anew with some other language or combination of other languages.
I could go on but I guess I made my point clear by now. All of this has made me feel unproductive when I program in C++ and made me lose confidence in the correctness of my own code which means I won't use it anymore, while I still use and rely on C code that I wrote more than 20 years ago. Maybe it's simply because I'm not a good C++ programmer, or maybe being quite good in C and other languages allows me to recognize what a lamer I actually am when it comes to C++, and that I will never be able to fully comprehend it.
Life is short...
In a low-level embedded environment some of the "software engineers" will have an EE background and have barely mastered C. C++ is more complex and some of these guys are simply afraid to learn a new language. Thus C is used as the lowest common denominator. (Before you suggest getting rid of these guys, they're at least as important as the CS majors who don't understand the hardcore analog stuff.)
Speaking from experience in having inherited and maintained both: a horrible design in C is difficult to understand, unwind, and refactor into something usable.
A horrible design in C++ is infinitely worse as random layers of abstraction send your brain careening around the codebase trying to figure out which code is going to be executed in which circumstance.
If I have to work with engineers who I know will not produce great designs, I'd much rather have the former than the latter.
I do not see any reason other then personal dislike, even for programming embedded systems and similar things. In C++ you pay overhead only for features you use. You can use the C subset of the C++ in some specific situations where C++ overhead is too high for you. This said, I think some C programmers overestimate the overhead of some C++ constructs. Let me list some examples:
- Classes and member functions have zero overhead compared to normal functions (unless you use virtual functions, in which case there is no overhead compared to using functions pointers)
- Templates have very little overhead (most often no overhead at all)
One valid reason would be when you are programming for a platform which does not have a decent C++ compiler (no C++ compiler at all, or a compiler exists, but is poorly implemented and imposes an unnecessary high overhead for some C++ features).
Why limit speaking in English? Perhaps you'd be a more creative author in Serbian.
That's the same argument, with obvious fallacies. If you have a task, and your comfortable tools solve the task efficiently, you'll likely use your comfortable tools for good reason.
C++ has a much longer learning curve. C has only few constructs you need to be aware of and then you can start coding powerful software. In C++ you need to learn the C base, then the OO and generic programming, exception, etc. And after a time you may know most of the features and you porbably can use them, but you still don't know how the compiler will translate them, what implicit overhead they have or not. This takes much time and energy.
For a professional project this argument may not count, because you can employ people that already know C++ very well. But in Open Source Projects, where C is still widley used, the people pick the language they like and they are able to use. Consider that not every OS-programmer is a professional programmer.
I'd like to follow up on Dan Olson's answer. I believe that people fear the potentially dangerous and counter-productive features of C++, and justifiably so. But unlike what Dan says, I do not think that simply deciding on a coding standard is effective, for two reasons:
- Coding standards can be difficult to strictly enforce
- It can be very difficult to come up with a good one.
I think that the second reason here is much more important than the first, because deciding on a coding standard can easily become a political matter and be subject to revision later on. Consider the following simplified case:
- You're allowed to use stl containers, but not to use templates in any of your own code.
- People start complaining that they'd be more productive if they just were allowed to code this or that template class.
- Coding standard is revised to allow that.
- Slide a slope to an overly complicated coding standard that nobody follows and use of exactly the kind of dangerous code that the standard was supposed to prevent, combined with excess bureaucracy surrounding the standard.
(The alternative that the standard is not revised in step 3 is empirically too improbable to consider and wouldn't be that much better anyway.)
Though I used to use C++ for just about everything a few years ago, I'm beginning to strongly feel that C is preferrable in low-level tasks that need to be handled by either C or C++ and everything else should be done in some other language entirely. (Only possible exceptions being some specific high-performance problem domains, wrt. Blitz++)
I use C, or at least export a C interface when I write library code.
I don't want ill-defined ABI hassles.
I've never seen any arguments for using C over C++ that I'd consider convincing. I think most people are afraid of certain features C++ offers, often justifiably. Yet this doesn't convince me because one can enforce whether or not to use certain features through coding standards. Even in C, there's much you'd want to avoid. Discarding C++ entirely is essentially saying it offers no tangible benefits over C that would help one write better code, which is a view I consider to be quite ignorant.
Additionally, people always seem to raise the situation of platforms where no C++ compiler exists. Certainly C would be appropriate here, but I think you'd be hard pressed to find a platform like that these days.
One point I've not seen raised yet, which I think is the most important:
Most of the libraries I use on a daily basis are C libraries with bindings for Python, Ruby, Perl, Java, etc. From what I've seen, it's a lot easier to wrap C libraries with 19 different language bindings than it is to wrap C++ libraries.
For example, I learned Cairo once, and have since used it in 3 or 4 different languages. Big win! I'd rather write a program that can be used again in the future, and writing one that can easily be adopted to other programming languages is an extreme case of this.
I know it's possible to bind C++ libraries, but AFAICT it's not the same. I've used Qt (v3 and v4) in other languages and it's not anywhere near as nice to use: they feel like writing C++ in some other language, not like native libraries. (You have to pass C++ method sigs as strings!)
C++ is probably a better language if you're writing a function to be used once, or if you think all the world is C++. C seems like an easier language if you're designing for language-portability from the start.
Windows kernel development doesn't support c++ (sadly).
You can read an entertaining rant about why Linus Torvalds favours C here
Native code on a mac is objective-c. Native code on a PC is c (window.h) or c++ (mfc). Both of these environments will let you use c with little or no changes. When I want a library of code to be cross platform ansi c seems like a good choice.
I can think of several reasons.
There may not be a satisfactory C++ compiler. C++ is a much bigger language, and I've run C compilers on systems that would not be able to handle modern C++.
The questioner, or people he or she works with, may be familiar with C but not C++.
The project may be in C. While it's possible to add some C++ features to C, that can easily lead to an unmaintainable mess. I'd suggest picking one language or the other (usually C++, when practical).
The questioner may have an obsolete view of C++'s learning curve. (When approached correctly, it's easier than C's. Most introductory books I've seen don't approach it correctly.)
Remember that C and C++ are two different languages, and are getting more different over time. Coding in both at once is a bad idea, and using a C-like subset of C++ misses most of the advantages of C++.
If you work in an environment with two languages, you might use C for some performance critical low-level functions and a more functional/high level language like C#/Java for the business logic. If C++ code is usedfor these functions ,C-Wrappers are required for JNI/unmanaged code around and this makes things more complex than solely using C.
I use C++ with C programming for two reasons:
vectorandstringto get the array memory management away from me- strict type checking and casts to warn and/or catch allthe nuisances I would miss otherwise.
So it is C really borrowing a few c++ but using the c++ compiler as much as I can. As someone else says in the answers, I find now I am actually picking up more C++ this way and where C would be too involving, I use C++. Monitor/Lock using RAII is one of these I've used recently when dealing with multi-threaded programs and another similar construct to open/close files.
I think C is more portable. I did some work about 5 years ago porting code to many flavours of unix (AIX,Irix,HPUX,Linux). The C code was easy to port but we had various problems porting some of the C++ code across. Maybe it was just immature development environments but i would much rather use C over C++ for this reason...
C is a simple language, C++ is not. For many people, C++ is simply too complicated to fully master, see http://en.wikipedia.org/wiki/C%2B%2B#Criticism.
Because of the complexity, different programmers usually only master different subsets of the language. It makes reading other people's code painful.
The complexity, pitfalls of the language add too much distraction, and sometimes hurt productivity. Instead of focus on the job itself, I often found myself fighting with the language itself. Java/python are more productive alternatives.
Debugging a broken C code is usually much more straightforward than debugging a broken C++ code.
Unlike Java/C#, the C++ standard library achieves little beyond the scope of the C standard library.
Some famous programmers like Linus Torvalds (Linux) and Richard Stallman (Emacs) dislike C++.
Most programmers take it for granted that everyone considers quality a high priority. That's not always the case. If you're use to C, C++ might seem like it's doing too much for you behind the scenes. The strictness of type checking in C++ might also seem confining. Many people are willing to risk introducing the kinds of bugs that C++ can help prevent to avoid these "nuisances."
There are three reasons I can think of. One is that C is more suited for embedded systems, due to the small size of its binaries and the wider availability of C compilers on any system. The second is portability: C is a smaller language, and and ANSI C code will compile anywhere. It's easier to break portability in C++. The last one is the language itself. C++ is harder, and is most definitely a very poorly designed language. Torvalds gripes are reported above. You may also want to look at the C++ Frequently Questioned Answers (http://yosefk.com/c++fqa/).
Portability may be an issue. Different to Gordon Carpenter-Thomp's answer, I would suggest that it's rather the runtime support of different versions of libstdc++ on different linux/unix versions. See this link for a good discussion about this. A little excerpt:
The runtime support code used by different parts of a C++ application needs to be compatible. If one part of the program needs to dynamic_cast or catch objects provided by another, both parts must agree on certain implementation details: how to find vtables, how to unwind the stack, and so on.
For C++ and a few other GCC-supported languages with similar features, such details are specified by a C++ ABI. Whenever the ABI used by GCC changes you'll end up with incompatible libraries produced by the different GCC versions. The same is true for plain C, but the C ABI is much simpler and has been around a lot longer so it's fairly stable.
I can follow many suggestions here in both directions. But in the end it comes down to a) comparable simple b) comparable complex.
I don't have an idea if someone has "invented" a sort of language complexity measurement.
On a scale from 0 - 10 I probably would rate C at 2 or 3 whereas C++ would be between 8-10. I'd argue C++ is one of the most complex languages but I do not know e.g Ada, PL1 or the like, so maybe it's not that complex in comparison to some other language.
C++ inherits all complexity of C so it can not be below the complexity level of C.
I for my part would be much more comfortable using some scripting language and C. So in the end one has to answer the following question. "Is more always better?"
The most useful thing I found in C is the lack of namespaces and overloads: function and symbol names are unique identifiers. To find the places where these symbols are used you can just grep through the source code files and search results will shows the locations.
It's essential when wiring in a new feature or component to an old and tangled system.
You cannot do this easily in C++, without a sophisticated call graph building tool.
Most people seem to think that C and C++ are somehow related, but they are sadly mistaken. C++ is a completely different language than C.
In C++, you think in terms of objects and how they are related to each other. In C, you think in terms of APIs. It's like the difference between day and 17.
A poor analogy: if someone adds Chinese to English and calls it English++, you probably wouldn't feel comfortable to add a Chinese line to your latest love letter, because it's so much easier to express love in this part of English++.
The following are all reasons why it may be beneficial to limit a project to C:
- faster compilation because the language is much simpler
- requires less runtime support, making it more suitable low-level environments
- much easier to interface with other languages
- supports variable sized arrays on the stack
- easier to read assembly code because there is no name mangling
- allows code produced by different compilers to be easily combined since it is the de facto standard application binary interface
참고URL : https://stackoverflow.com/questions/649789/what-would-be-c-limitations-compared-c-language
'IT story' 카테고리의 다른 글
| Facebook Android 키 해시 생성 (0) | 2020.07.19 |
|---|---|
| Android Lint가 번역되지 않은 문자열에 대해 불평하지 않도록하십시오. (0) | 2020.07.19 |
| 프로덕션 서버로서의 Webrick 대 Thin 또는 Unicorn? (0) | 2020.07.19 |
| 마이크로 서비스 인증 전략 (0) | 2020.07.19 |
| PHP / Perl을 통해 사용자 브라우저에 PDF 파일 표시 (0) | 2020.07.19 |