C/FORTRAN set double underflow to zero - c++

I have a legacy FORTRAN project with some very intense computations. I want this math code to be accessed by C/C++ code, so I built a FORTRAN dll, imported it in C/C++ and started to receive floating-point underflows from my FORTRAN dll.
At the same time, the FORTRAN dll code executes fine if I call it from a FORTRAN application.
Finally, I found out that the compiler I use (it's an FTN 95 integrated into VS2013) has an option (/UNDERFLOW). If this flag is not specified, all underflows are converted to zeroes by default. That happens in the FORTRAN app. When I use C code to execute methods from this dll, I receive underflows.
So, the question is: is there any way to force VC++ compiler to convert underflows to zeroes?
P.S.: yes, I understand that it is stupid to rely on a code that throws floating-point exceptions all the way. However, this code is old and at this point it is impossible to completely rewrite it using up-to-date techniques.

So, problem was with FTN95 compiler. The mentioned above flag (/UNDERFLOW) seems to be useful only when one build an application. The effect of this flag is neglected when the target output is DLL. Instead of this I found a compiler directive that is accessed through call to MASK_UNDERFLOW#() subroutine. After inserting an explicit call to this subroutine in the FORTRAN function that was throwing underflows and recompiling the DLL, I've managed to successfully launch a C program and perform necessary computations using functions from FORTRAN dlls. Also, an fp:/except- VC++ compiler flag was used to ensure that no other underflows will affect execution of C program.

Related

Forcing strong type checking with Fortran functions at compile time

I'm helping renovate a legacy code base in Fortran which has interface definitions for functions / subroutines.
The issue I am facing is that some of those interfaces are out of sync with the actual function definitions and the compiler (silverfrost) is not catching these at compile time. This leads to run time errors.
Ignoring the specific compiler I am using for now, does Fortran have a method for handling this without repeating the function definition? For example, in C#, Java etc. I can declare a function and call it from elsewhere in the project and the compiler makes sure the caller and target function are compatible.
Does GNU Fortran or the Intel Fortran compiler make this any less fragile?
If you put procedures in MODULEs and USE the MODULEs, the compiler will check that procedures are called with the correct arguments.

summary of potential dll compatibility issues?

When an (unmanaged) Win32 program (or other DLL) calls an (unmanaged) Win32 DLL, my understanding is that there are a number of potential incompatibilities that could cause problems/crashes.
For instance, if program P calls DLL D, and P was compiled with Visual Studio 2013 to target Windows SDK version 8, and D was compiled to with Visual Studio 2017 to target Windows SDK version 10, my understanding is they will access different msvc runtime DLLs, which can cause problems. For instance, if D allocates memory with new and passes it back to P, and P tries to delete it, there is a crash because P and D are using two different runtimes, each maintaining their own heap.
Similarly, if P is built with run-time type information (RTTI) and D is not, my understanding is there can be crashing incompatibilities when, say, P allocates a class instance (to a type that each referenced in a common .h file) and passes it to D, because of differences in the virtual function table and/or in the padding between structure fields.
I'm trying to understand what other incompatibilities might exist. Ideally I'd like to find a complete list. Here are some possibilities that come to mind:
Struct Member Alignment (similar to the RTTI issue)
Use Multi-Byte Character Set vs. Use Unicode Character Set (could cause problems if string objects are passed/returned?)
Omit (vs. do not omit) frame pointers (or perhaps this does not apply because the function call mechanism across programs/DLLs is different from the internal function call mechanism this flag relates to?)
Enable (or disable) C++ Exceptions (exception handling works across a DLL call if they are both built with exceptions enabled and using the same runtime?)
Others?
EDIT
I asked this question as a general curiosity, but also because I was having random heap corruption using a DLL in my program, and I was trying to figure out what could possibly be the problem.
My issue turned out to be that I was linking against an outdated DLL import library. I'm not exactly sure why the program started without error, and why it basically ran okay but with intermittent heap corruption. I believe it could only start without error if the new DLL offered a superset of the functionality provided by the old DLL import library. And then I'm not sure if the mechanism is a mismatch in C/C++ runtime libraries, or perhaps a change in a function's parameters without a breaking change in function signature?
In any event, I guess linking against an outdated DLL import library can be added to the list, although it's a less innocent mistake than the others mentioned.
A very common mistake is using standard library stuff or other compiler implementation/version related features in dll-interfaces.
This will normally only work if both parties (dll and its user) use the same version of the compiler and even then there may be incompatibilities when one of them is build with DEBUG enabled and the other with NDEBUG.
Only use c-compatible types etc. in dll-interfaces.

Visual Studio warning C4743: How does Whole Program Optimization affect _fltused?

So at work I'm working on a C++ application that runs without the C++ run-time library. We're using Visual Studio 2005, and have the /NODEFAULTLIB switch specified.
The solution is organized such that there are various static library projects, and then a single executable project which uses those libraries. The libraries are mostly common libraries tracked in a separate repository. They can be changed, but it's best for us not to, if we can avoid it.
One of those common libraries uses floating-point math. Since we don't have the C++ run-time, we have defined these routines ourself (ex: _ftol2_sse for converting float to int).
From my (rather limited) understanding of the low-level details, the compiler emits the symbol _fltused signal that floating point math routines need to be used.
For some reason, one of the other common libraries decides to define this symbol manually, as
extern "C" { unsigned short _fltused = 0; };
When I enable Whole Program Optimization and Link-time code generation, I get
warning C4743: '_fltused' has different size ...
when linking. I don't know why we have it declared as an unsigned short instead of int, but that's how it is.
When I don't enable Whole Program Optimization or LTCG, the warning goes away.
I guess I have two questions.
Can I safely ignore this warning?
What optimization is being made that causes the warning to occur? I'm not sure why it's not a warning without Whole Program Optimization enabled.
UPDATE
I was able to track down the original author of the code, who admits that it is a bug that occurred when rewriting the code from assembly language. He agrees with me that the warning is harmless, since _fltused is never actually used directly.
I think I can answer 2 at least. It's not any specific optimization being made. It's the fact that whole program optimization forces the compiler to keep some representation of the whole program available to optimize from, and from that intermediate representation it's able to determine that the same variable has different sizes. When whole program optimization is not enabled the compiler only looks at each source file separately and doesn't see that two different files define different types for that symbol.
All that said I'm 99% sure your program violates the one definition rule, "undefined behavior, no diagnostic required". If you have any chance to fix it you should, against something as simple as a compiler patch breaking your code.

Pascal DLL in C++ aplication on ARM platform

I have a huge amount of code written in Pascal and I need to use it in a C++ application running on an embedded PC with ARM9 processor. My idea was cross compiling Pascal code to dll libraries which I wanted to include in my C++ app. I tried to install Lazarus but I can't get work its cross compiler and I tried to install compiler directly to the embedded PC with similar result. C++ cross compiler works perfectly. Is there any way how to get Pascal code working in C++ application on different platform? I will provide any additional info if needed.
Additional info:
the embedded pc is for use in extremely low temperatures so it has low ram (32MB) running a trimmed Linux and there is only a little free space left on its flash memory (i have to use the SD card for all files)
I don't think anyone can conclusively answer your question, but some hints:
You will need to find a way to communicate between the C++ and Pascal code. This may simply be a case of defining any interface function as a C or C++ style function. But for example strings in Pascal are often NOT standard C or C++ style strings, so will need some extra handling to work out right. Structs (RECORD in pascal) and classes will require even more careful handling as to how they interface between the C++ and Pascal code - in most cases, it will become a full marshalling solution (that is, convert to a byte-stream, and then convert back to correct type at the other end).
Cross compilation of the Pascal code relies on having a Pascal compiler that matches your Pascal code AND your target. If you can't compile your code to the correct target, all other parts of the project will fail... There is a "standard" for Pascal, but most compilers have a range of extensions.
Have you considered making the Pascal code a standalone application that produces results as a file, rather than directly interfacing to the C++ code? Reading a file that you can control the format of can be a much easier solution than trying to interface one language to another.

C++ Windows Compiler for smallest executables

guys I want to start programing with C++. I have written some programs in vb6, vb.net and now I want to gain knowledge in C++, what I want is a compiler that can compile my code to the smallest windows application. For example there is a Basic language compiler called PureBasic that can make Hello world standalone app's size 5 kb, and simple socket program which i compiled was only 12kb (without any DLL-s and Runtime files). I know it is amazing, so I want something like this for C++.
If I am wrong and there is not such kind of windows compiler can someone give me a website or book that can teach me how to reduce C++ executable size, or how to use Windows API calls?
Taking Microsoft Visual C++ compiler as example, if you turn off linking to the C runtime (/NODEFAULTLIB) your executable will be as small as 5KB.
There's a little problem though: you won't be able to use almost anything from the standard C or C++ libraries, nor standard features of C++ like exception handling, new and delete operators, floating point arithmetics, and more. You'll need to use only the features directly provided by WinAPI (e.g. create files with CreateFile, allocate memory with HeapAlloc, etc...).
It's also worth noting that while it's possible to create small executables with C++ using these methods, you may not be using most of C++ features at this point. In fact typical C++ code have some significant bloat due to heavy use of templates, polymorphism that prevents dead code elimination, or stack unwinding tables used for exception handling. You may be better off using something like C for this purpose.
I had to do this many years ago with VC6. It was necessary because the executable was going to be transmitted over the wire to a target computer, where it would run. Since it was likely to be sent over a modem connection, it needed to be as small as possible. To shrink the executable, I relied on two techniques:
Do not use the C or C++ runtime. Tell the compiler not to link them in. Implement all necessary functionality using a subset of the Windows API that was guaranteed to be available on all versions of Windows at the time (98, Me, NT, 2000).
Tell the linker to combine all code and data segments into one. I don't remember the switches for this and I don't know if it's still possible, especially with 64-bit executables.
The final executable size: ~2K
Reduction of the executable size for the code below from 24k to 1.6k bytes in Visual C++
int main (char argv[]) {
return 0;
}
Linker Switches (although the safe alignment is recommended to be 512):
/FILEALIGN:16
/ALIGN:16
Link with (in the VC++ project properties):
LIBCTINY.LIB
Additional pragmas (this will address Feruccio's suggestion)
However, I still see a section of ASCII(0) making a third of the executable, and the "Rich" Windows signature. (I'm reading the latter is not really needed for program execution).
#ifdef NDEBUG
#pragma optimize("gsy",on)
#pragma comment(linker,"/merge:.rdata=.data")
#pragma comment(linker,"/merge:.text=.data")
#pragma comment(linker,"/merge:.reloc=.data")
#pragma comment(linker,"/OPT:NOWIN98")
#endif // NDEBUG
int main (char argv[]) {
return 0;
}
I don't know why you are interested in this kind of optimization before learning the language, but anyways...
It doesn't make much difference of what compiler you use, but on how you use it. Chose a compiler like the Visual Studio C++'s or MinGW for example, and read its documentation. You will find information of how to optimize the compilation for size or performance (usually when you optimize for size, you lose performance, and vice-versa).
In Visual Studio, for example, you can minimize the size of the executable by passing the /O1 parameter to the compiler (or Project Properties/ C-C++ /Optimization).
Also don't forget to compile in "release" mode, or your executable may be full of debugging symbols, which will increase the size of your executable.
A modern desktop PC running Windows has at least 1Gb RAM and a huge hard drive, worrying about the size of a trivial program that is not representative of any real application is pointless.
Much of the size of a "Hello world" program in any language is fixed overhead to do with establishing an execution environment and loading and starting the code. For any non-trivial application you should be more concerned with the rate the code size increases as more functionality is added. And in that sense it is likley that C++ code in any compiler is pretty efficient. That is to say your PureBasic program that does little or nothing may be smaller than an equivalent C++ program, but that is not necessarily the case by the time you have built useful functionality into the code.
#user: C++ does produce small object code, however if the code for printf() (or cout<<) is statically linked, the resulting executable may be rather larger because printf() has a lot of functionality that is not used in a "hello world" program so is redundant. Try using puts() for example and you may find the code is smaller.
Moreover are you sure that you are comparing apples with apples? Some execution environments rely on a dynamically linked runtime library or virtual machine that is providing functionality that might be statically linked in a C++ program.
I don't like to reply to a dead post, but since none of the responses mentions this (except Mat response)...
Repeat after me: C++ != ( vb6 || vb.net || basic ). And I'm not only mentioning syntax, C++ coding style is typically different than the one in VB, as C++ programmers try to make things usually better designed than vb programmers...
P.S.: No, there is no place for copy-paste in C++ world. Sorry, had to say this...