Is there a way to allow for implicit conversions in c++? - c++

I need to use pieces of a C library in a C++/CLI project. I forced the c files to compile as c++, the problem is that the library uses a lot of implicit enum to integer comparisons which c++ wont allow. Now I could just properly cast all of these but I'd like to achieve the result without modifying the original library code if possible (since the library is still being developed and I'd like to have plug n play capability). Is there a way to allow c++ to implicitly convert those enums?

The pedant answer is No.
The C++ Standard is stricter than the C Standard in that regard, and implicit casts from integer to enumerator or from void* to T* do not work out of the box.
You have a couple solutions ahead of you:
your compiler might have such a switch, it is not rare to have compiler switches to trigger non-Standard behaviors (often seen as "features"); I do not know of such switch but there are so many...
you could compile C code as C (possibly linking into a separate library if necessary)
you could edit the C code so it compiles as both C and C++
and finally, since it is a library in development, you could ask the authors to make sure their code compile as both C and C++

Related

Compiling C99 files with C++ compiler

Have not found the exact question i am asking in either google or here, everything talks about wanting to call c++ from c code or some part being compiled with c compiler and some other with c++ and then later linked together and the problems that arise from that which i do not want.
I want to compile and link C99 files with C++ compiler of Visual Studio in my all C++ application and be able to call the c functions without errors and problems.There will be no c linker involved or compiling some part with different compilers and linking together later, or any kind of trick. The headers are from C library (libcurl) and some others as i want to use them in my application. I do not want to use the C++ bindings i want to compile c code as c++. Can i trust c code be compiled as C++ code without major refactoring? What to do differently than when including C++ headers? What incompatibilities to expect?
In theory, C code should be able to be compiled as C++ code. At some point Dr.Stroustrup made the point that all code from ANSI C edition of the K&R compiles with a C++ compiler and has the same semantics as the code compiled with a C compiler has (this was construed that all ANSI C code would be valid C++ code which is, obviously, not the case, e.g., because many C++ keywords are not reserved identifiers in C).
However, certain idioms in C will require substantial changes to the C code if you want to compile the code with a C++ compiler. A typical example is the need to cast void* to the proper type in C++ which isn't needed in C and it seems it is frowned upon casting the result from malloc() to the proper pointer type although the effect is that it prevents the C code from being compiled with a C++ compiler (in my opinion a good think, e.g., because there the tighter rules may result in discovering problems in the C code even if the production version is being compiled with a C compiler). There are also a few subtle semantic differences as far as I know, although right now I can't easily pin-point one of them. That is, the same code compiled with a C and a C++ compiler may have defined but different results for both cases.
In practice, I doubt that you can simply compile a non-trivial body of C code with a C++ compiler and get a program which behaves the same as the original C code. If the C program you envision to compile with a C++ comes with a thorough set of test cases it may be feasible to port the code to C++ but it will involve more work than merely renaming the file from <name>.c to <name>.cpp. I could imagine that a tool could do the required conversions (a compiler compiling C source to C++ source) but I'm not aware of a such a tool. I'm only aware of the opposite direction yielding entirely unreadable code (for example Comeau C++ uses C as a form of portable assembler).
If you want to do this using visual studio, then it is not possible. MSVC doesn't support C99.
C and C++ are two different, but closely related, languages. C++ is nearly a superset of C++, but not quite (in particular, C++ has keywords that C lacks).
If your code depends on C99 features (i.e., features that are in C99 but not in C90), then you may be out of luck. Microsoft's C compiler does not support C99 (except for a few minor features; I think it permits // comments), and Microsoft has stated clearly that such support is not a priority. You may be able to modify the code so it's valid C90, depending on what features it uses.
Microsoft Visual Studio supports compiling both C and C++ (though it tends to emphasize C++). If you can get your C code compiling with the MS C compiler, I suggest doing just that rather than treating it as C++. C++ has features, particularly extern "C", that are specifically designed to let you interface C and C++ code. The C++ FAQ Lite discusses this in section 32.
If you really need to compile your C code as C++ for some reason, you can probably do so with a few minor source changes. Rename the source file from foo.c to foo.cpp, compile it, and fix any errors that are reported. The result probably won't be good C++, but you should be able to get it to work. There are a few constructs that are valid C and valid C++ with different semantics, but there aren't many of them, and you're not likely to run into them (but you should definitely keep that in mind).
If you want to continue maintaining the code as C++, my advice is to go ahead and make the changes needed to do that, and then stop thinking of it as C code.
The actual need to compile the same code both as C and as C++ is quite rare. (P.J. Plauger, for example, needs to do this, since he provides some libraries intended to be used in either language.) In most cases, C++'s extern "C" and other features are good enough to let you mix the two languages reasonably cleanly.

Call C function using Objective C class instance

I have an Objective C class with a C type method in it. I have to link a C++ library and a C library with my code. If I make the library calls from any Objective C function, I get linker errors, that it can't find the symbols.
refer using c++ static library in objective c
But I need to call that C function somehow. Is there any alternative? In case of only C libraries, I could make the library calls from objective C method, but C++ library doesn't allow me to do that. I don't know why.
In my experience, if the program uses any C++ classes, you should be doing the linking with a C++ compiler so as to get the correct C++ libraries linked. With just C and C++, that's fairly straight-forward.
Throw Objective C into the mix and you could get into some difficulties — your question implies you are getting into some difficulties. I have not tried this, but...
You will need to be sure that the correct C++ libraries are linked, the correct Objective C libraries are linked, as well as any stray C libraries that you need. If you can determine the libraries that are linked when you build an Objective C program, you may be safe enough simply to link with the C++ compiler and list the Objective C and pure C libraries that you need. Fingers crossed, that's all. If there are complicated setup requirements for Objective C (as well as the complex requirements for C++), then you may still have difficulties. On the whole though, you are likely to be OK.
If someone with definitive experience says something different, go with their solution (if it works for you). But the best I can offer is 'link the program with the C++ compiler'.
I'm not quite sure what code is causing you problems but if you want to call a C-style function which is defined in a C++ file from a different C file, make sure to mark the function as extern "C" to avoid name mangling.

What is a handy way to make a novel Fortran library callable from C

I'm working on a small Fortran library (novel code) which is being called from several C/C++ applications. The library is of such kind when almost every subroutine could be separately called from application. So I need to provide C interface for those subroutines.
I can use modules, which are very comfortable by itself. But then I need either to decode manually module name mangling (which isn't very hard for gfortran, but looks bad) or use bind(C,name="some_name") clause. The last one leads to compiler warnings like subroutine parameter wasn't explicitly made interoperable (so compiler wants me to replace double precision with real(kind=C_DOUBLE), for example). And I should in this case to replace almost every variable in a library with such ugly declarations, which results to bad-reading code.
I can use subroutines, when every file in a library consists of several subroutines (this is the way that I do now). Explicitly interfaces are fed between them with interface ... include "otherfile_h.f90" ... end interface which isn't very comfortable. Name mangling is rather simple in this case, and library subroutines could be easily directly called from C.
The approach that I use (bullet #2) requires more typing and it is error prone because of duplicating definitions in source/header files. Is there a better way to keep sources clear and readable with smart C interface?
The modern way to mix Fortran and C is to use Fortran's ISO C Binding. This will make your code portable since the ISO C Binding is part of the language standard. Manually figuring out the name mangling is compiler specific and might not work on another compiler. "Double precision" is not considered a best practice declaration for modern Fortran (see, e.g., Extended double precision and http://fortranwiki.org/fortran/show/Modernizing+Old+Fortran). The modern way is to use "real (kind=XYZ)". The concept of the language is that typically the programmer uses SELECTED_REAL_KIND intrinsic function to define an constant (e.g., MyDouble) for the precision that they need. If the precision that you need is C_DOUBLE, then it is very appropriate Fortran to use that kind value. This is not an ugly declaration. (I don't understand your bullet #2.)

Implementing C library function in C++

What are the disadvantages of implementing C library in C++? The library is going to be used to build Windows application for regular PC using Visual Studio 2008 or newer. It is not clear why the specs state that it should be C library. I am guessing that what they want is plain C-API, not pure C lib. But my boss disagrees.
Anyway, what I want to do is to extern "C" all function declarations and use C++ in implementation files. I did some testing and everything worked just fine even when the application was compiled as C (by changing project option in Visual Studio).
I've seen people do that for, say, exposing STL collections to C programs. If you are sure that the library will only be used in environments with sane C/C++ compilers (say, VS and gcc only) I think this is a pretty safe thing to do from the technical perspective. N
ow, it sounds like you have some sort of outside requirement at play here, but obviously we can't comment on that. Might be worse double checking with the requirements source?
UPDATE: oh, I should mention that it will affect the DLLs that your library will require. Like the C++ runtime DLL will need to be loaded in addition to CRT.
The extern c is used like all the time to port some functionality from c to c++. For instance the new operator inturn calls the malloc() from std c. This is one good example of c library being given a c++ look. new operator makes it much more easy to allocate memory and in addition to that it also allows a lot of functionality like operator overloading which is not available in c. My guess would be to add more functionality to and to make neat interfaces.
If you are considering about disadvatanges then it might be related compiler specific problems where the ABL generated for a c++ program differs from that of the C and if the compiler is not able to differentiate between the two then you struck with it.
I am not sure if this is what you are seeking for, if not try this link it might be of some assistance.
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=180
If they are going to use it for a C programm, i.e. the main() function is compiled by a C compiler, then you have to be very carefully with your C++ library. The problem is that the c programm will not execute any constructor for static variables. So you have to omit the usage of any static variables with constructor. This is easy for your library itself, but you have to check every call to a library C++ function if it relies on the existance of a static initialized variable (e.g. std::cout, std::cin etc.).

Is there anything special I need to do to use C code in my C++ program?

Note: I am using g++ version 4.3.4 to compile my C++ code.
So far, whenever I've wanted to use C style language elements in my code it seems that I can just include the C stuff mixed in and alongside my C++.
I know C++ is mostly backwards compatible with C... so I guess my questions are these:
What parts of C are not forwards compatible with C++?
Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?
What is the proper way to have C and C++ code in the same .cpp file?
Can I continue to use g++ to compile my hybrid code?
For this question, I am mostly concerned with a solution that deals with a single .cpp file and a single g++ command to compile it. I don't really care about linking stuff at this point.
Picking out a couple of questions:
"What is the proper way to have C and C++ code in the same .cpp file?"
"Can I continue to use g++ to compile my hybrid code?"
If you want to mix C-style C++ in the same file as regular C++, just go ahead and do it. You can trust the compiler to pick up any issues - they will be minimal and not affect the structure. By the sound of it, you are not interested in getting C-linkage for its own sake, so even if the C-Code is in its own file, compile it as C++. As a matter of fact this is often done as a way of migrating from C to C++.
If you take this approach, your code is not truly hybrid C/C++. It is C++ with some of the code using C-style procedural idioms. C++ is fully intended to support this.
"Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?"
It depends where you are using it and why. Well structured C code is good code. Sometimes C+ is much better than C at particular problems. Think hard before using C-style dynamic memory management. You will deserved to be laughed at if you use raw malloc()/free() and get it wrong.
I suggest that if you embark on this approach, you might later take the time to look back and consider whether or not you would have been better to use C++ idioms instread of procedural C.
A big gotcha with linking C and C++ code is that the C++ compiler needs to know that it is linking against functions that use the C calling conventions instead of the C++ calling conventions. To that end, you often have to wrap your C header files in something like this:
#ifdef __cplusplus
extern "C" {
#endif
... C function declarations here ...
#ifdef __cplusplus
}
#endif
For lots of details, see the C++ FAQ.
C++ is almost a superset of C. Therefore, pretty much any feature you can use in C is valid in C++ (but not the other way around).
People might laugh at you for coding some stuff like you would in C, but ignore them. I don't think it's naive, but that may make me naive. I can't tell.
There is no [real] way to seperate C and C++ code in the same file. It just goes with each other, because when you compile it as C++, it's not C any more. So "C alongside C++" is not really the way to think about it.
The only difference between thing in C that would keep code from compiling as C++ that I am aware of (besides C++ having more keywords) is the issue with void*s. In C, they will implicitly cast to any pointer type, but in C++, you have to have an explicit cast to cast them to another pointer type. There might be others, but I don't know them.
Oh, also, C++ doesn't support "default int". I don't know if it's still valid C these days, but if you leave off the type of a variable or the return type of a function, the compiler would just use int. C++ doesn't do that.
Most good C practices make for fine compiling C++. A couple of extra pointer casts and renamed identifiers will make for legal C++.
In style, however, C-style code is considered to be horrendous C++. The fact that you can write C-style code in C++ should be used if and only if you can't afford to write it in C++ to begin with- i.e., if it's legacy code.
Will professional programmers laugh at me if I continue to naively
stick C stuff into my C++ code?
Basically, yes. C-style coding is known in C++ as "horrendously unsafe", just to begin with. That kind of code is written only by people who don't genuinely know how to use C++. By that, I don't mean doing very low-level stuff like bit twiddling or binary re-interpretation, but things like pointer casting or manual resource management, and that will get you laughed at.
This is too broad a question; you should break it up into several. There's a way to link together C and C++ object files; C++ is backward compatible with C, and you can use C++ compiler to compile C code.
But, consider this code:
int main(void)
{
int class = 0;
int private = 1;
return private-class;
}
It's valid C code, and obviously won't compile on any C++ compiler if compiled as C++ code. Just an example.
Well, the obvious key difference is that C++ is object-oriented by design and C is not. That said, you shouldn't have any horrific show-stopping issues compiling C code with g++ unless you run into one of the nasty gotchas that are floating around. You can find a lot of good references for them, and I admit that my answer is far from exhaustive.
It's true that you cannot implicitly cast from void* in C++; it won't compile, whereas you'll see it fairly often in C.
You also have to explicitly declare functions in C++ before you use them, where you don't necessarily have to in C. (It's good form to do so, but not all C programmers do.)
http://www.cprogramming.com/tutorial/c-vs-c++.html Now that I'm out of things off the top of my head, this is a good little reference; I use it frequently.