error occured when fortran code called c code - c++

I have used a method in a reference book about fortran codes calling c codes. The method is that if your function name in the c codes are capitalized, you may not make additional changes in your fortran code. The following is my code.
Source1.f90:
program main
implicit none
call c_subprint()
endprogram
ccode.c:
#include <stdio.h>
#include <string.h>
#ifdef _cplusplus
extern "C" {
#endif
void _stdcall C_SUBPRINT()
{
int a;
printf("%s\n","kk");
scanf("%d",&a);
}
#ifdef _cplusplus
}
#endif
The error message is that the main function cannot find out _C_SUBPRINT(LNK2019). But I have already added the .lib generated by the c code to the fortran code. And my code is almost the same as that in the reference book. what is wrong?

Different Fortran compilers generate calls differently. Many add underscores to routine names to avoid name conflicts with C-code. Its very hard to say whether or not you should exactly follow the example of an unnamed reference book. In the past, to mix Fortran and C, you have to understand some of the compiler internals. Here the Fortran compiler appears to have added an underscore to the start of the name. You could probably fix the problem by adding that in your C++ code. But that won't be portable and in principle could change with compiler versions. There is a better way: the Fortran ISO_C_Binding. This is part of the Fortran language standard and therefore standard and portable. Examples are given in the gfortran manual in the Chapter "Mixed-Language Programming" and in other questions on Stackoverflow.

From the inclusion of _stdcall I deduce you are probably using a Windows platform. Unfortunately I'm working on a Mac, so things may not be exactly the same. However, the following works for me (small changes from your code) to get a mix of Fortran and C code working together. Note - on my Mac, the gcc compiler does not include Fortran, so I used a separate Fortran compiler gfortran which I downloaded from a link at http://hpc.sourceforge.net - where instructions for installation could also be found.
program src1.f90:
program main
implicit none
call C_SUBPRINT()
endprogram
program ccode.c:
#include <stdio.h>
#include <string.h>
void c_subprint_()
{
printf("hello world!\n");
}
Note I took out the #ifdef sections - I was using pure C, so it was not needed; more importantly, note the underscore after the function name
I compiled these two modules as follows:
gcc -c ccode.c -o ccode.o
gfortran src1.f90 ccode.o -o hello
After which I can run
./hello
And get the expected output:
hello world!
Without the underscore, the linker complains about unknown symbols. There is an option in the compiler to turn off "name mangling" with the underscore. You can check your specific compiler to see how that would be done - but that's almost certainly the problem you are having.

Related

"no main" function for linking or execution in C++ [duplicate]

This question already has answers here:
How to change entry point of C program with gcc?
(4 answers)
Closed 5 years ago.
I am trying to compile a function (not called main) that can be integrated in another code or directly executed (after linking).
I try it one my mac, and work well.
I finally test it on Linux (CentOS and ubuntu). However, the task looks harder as expected on Linux.
The source code is the following one (just to explain the problem)
test.cpp:
#include <cstdio>
#ifdef __cplusplus
extern "C" {
#endif
int test(int argc, char const *argv[]);
#ifdef __cplusplus
}
#endif
int test(int argc, char const *argv[]) {
fprintf(stderr, "%s\n", "test");
return 0;
}
Compilation line on MacOS
g++ -c test.cpp -o test.o && g++ test.o -o test -e _test
and on Linux
g++ -c test.cpp -o test.o && g++ test.o -o test -e test
I try on my MacOS with clang, g++ and Intel compiler, all 3 works fine.
And I try with g++ and the Intel compiler on Linux, always, the same error.
usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
Any advice, explanation or solution, on what I am doing wrong or missing would be very helpful.
Thanks
Edit:
Currently, I have a "define" to create a main, but if we have lots of function we are obligated to do two compilations each time (one for the function version and one for the execution) and make finally the code heavier.
Like discussed in this topic is there a GCC compiler/linker option to change the name of main?
To don't do a XY I inherited from a bunch of small programs that I want to put to gather, that it is easier to use (for remote execution ...). However, each one need to be able to be executed independently if needed, for debugging,... I hesitate, between using "execv" and just convert each main as a function. I probably take the bad chose.
Edit:
The final goal is to be able to have independent programs. But that we can call from an external software too.
Solution:
The solution looks to be, to a call to the main through a dlopen
You cannot do that (and even if it appears to work on MacOSX it is implementation specific and undefined behavior).
Linux crt0 is doing more complex stuff that what you think.
The C standard (e.g. n1570 for C11) requires a main function for hosted implementations (§5.1.2.2.1) :
The function called at program startup is named main. The implementation declares no prototype for this function.
And the C++ standard also requires a main and strongly requires some processing (e.g. construction of static data) to be done before main is running and after it has returned (and various crt0 tricks are implementing that feature on Linux).
If you want to understand gory details (and they are not easy!), study the ABI and the (free software) source code of the implementation of the crt0.
I am trying to compile a function (not called main) that can be integrated in another code
BTW, to use dynamically some code (e.g. plug-ins) from another program, consider using the dynamic linker. I recommend using the POSIX compliant dlopen(3) with dlsym(3) on position-independent code shared libraries. It works on most Unix flavors (including MacOSX & Linux & Solaris & AIX). For C++ code beware of name mangling so read at least the C++ dlopen mini howto.
Read also the Program Library HowTo.
Problems with libraries, they cannot be executed, no ?
I don't understand what that means. You certainly can load a plugin then run code inside it from the main program dlopen-ing it.
(and on Linux, some libraries like libc.so are even specially built to also work as an executable; I don't recommend this practice for your own code)
You might take several days to read Drepper's How To Write Shared Libraries (but it is advanced stuff).
If you want to add some code at runtime, read also this answer and that one.
The final goal is to be able to have independent program. But that we can call from an external software too
You can't do that (and it would make no sense). However, you could have conventions for communicating with other running programs (i.e. processes), using inter-process communication such as pipe(7)-s and many others. Read Advanced Linux Programming first and before coding. Read also Operating Systems : Three Easy Pieces
The solution looks to be, to a call to the main through a dlopen
Calling the main function via dlopen & dlsym is forbidden by the C++ standard (which disallows using a pointer to main). The main function has a very specific status and role (and is compiled specially; the compiler knows about main).
(perhaps calling main obtained by dlsym would appear to work on some Linux systems, but it certainly is undefined behavior so you should not do that)

Calling Ada from C++ in Eclipse

I am trying to create a program that is completely hosted in Eclipse, starts in C++, and calls Ada. I have GNATBench loaded, and can run Ada programs without a problem. What I cannot do is have a C++ project call an Ada project.
After hunting around, I found and executed the code shown below using a make file.
http://www.pegasoft.ca/resources/boblap/book.html
I also found a post stating that my goal has been done.
http://blogs.windriver.com/parkinson/2009/10/yesterday-adacore-announced-the-release-of-gnatbench-231-its-ada-integrated-development-environment-eclipse-plugin-which.html
What else do I need to include to have C++ in Eclipse call Ada in Eclipse?
USING MAKE FILE:
$ c++ -c test.cc
$ gnatgcc -c test_subr
$ gnatbind -n test_subr
$ gnatgcc -c b~test_subr
$ gnatlink -o main test.o test_subr.ali --link=c++
$ ./main
 
CPP Code:
//main.cc
#include extern "C" void adainit(void);
#include extern "C" void adafinal(void);
#include extern "C" void ada_subroutine(void);
int main(int argc, char **argv)
{
puts("C++ main");
adainit();
ada_subroutine();
adafinal();
puts("C++ done");
return 0;
}
Ada Code:
package Test_Subr is
procedure Ada_Subroutine;
pragma export(CPP, Ada_Subroutine);
end Test_Subr;
with Ada.Text_IO;
use Ada.Text_IO;
package body Test_Subr is
procedure Ada_Subroutine is
begin
put("IN ADA");
end Ada_Subroutine;
end Test_Subr;
Have you tried using the External_Name parameter of the Export pragma? (IIRC, C++ linkages can get quite mangled.)
pragma Export
( Convention => CPP,
Entity => Ada_Subroutine,
External_Name => "Ada_Subroutine "
);
I don’t know Eclipse; but, how would you get a C++ project in Eclipse to call up another C++ project? or one written in C?
You might be able to get Eclipse to build the Ada as a library and invoke that from the C++?
In the general case, you need to use extern C on the C++ side and pragma exprort (C, .. on the Ada side to get both linkages (parameter passing schemes) the same. However, if you are using gcc for both Ada and C++ then you could use pragma export (CPP instead.
There is one more nit you have to be aware of. If your "main" (the program's entry point) is not written in Ada, then you will need to manually invoke Ada's elaboration process (via the routine adainit()) once before calling anything. Likewise you should in most cases call adafinal() before exiting your program.

calling C++ function from fortran not C

is it possible to call a C++ function from FORTRAN such as
#include <iostream.h>
extern "C"
{
void single_cell(void)
{
cout<<"Hi from C++";
}
}
So when I am using C it is working fine but with the C++ function it gives errors like
Undefined error to cout etc
Both g++ and gfortran, used as linkers, bring in extra libraries. That is why the Fortran/C++ combination is trickier than the Fortran/C combination ... just using the correct compiler as the linker won't work, you need to add a libary. Already suggested is to link with gfortran and specify the C++ runtime libraries. You can also link with g++ and specify the Fortran runtime libraries. See Linking fortran and c++ binaries using gcc for the details of both approaches.
Assuming you could have your Fortran code call into a C function, the problem is not the code but rather how you are linking. When you're linking C++ objects you need to also pull in the C++ runtime. If using GCC, link with the g++ command and it will pull in the parts you need.

Call C/C++ code form a fortran program in visual studio? (How to compile mixed C and fortran code in visual studio)

i am looking for a way, how i can integrate a c++ code with fortran code (i want simply call some C/C++ functions in the fortran code).
I have found some proposals for gcc or console compilers, but i have not any idea how to translate this approach to solve integrationproblem within the visual studio.
At the time I am thinking about creating a dll form c++ code and calling it from Fortran code.
Has someone already seen a solution? Or what is about overhead for calling function from dll? My fortran code transfers a lot of memory into C function, is there any problems, if i would solve this problem with dll?
thx.
PS
I am using Visual Studio 2008 Prof and Intel compilers 10
PPS
I think, i have to specify more concrete, what i want: i want to compile a fortran project in visual studio, which uses some C functions.
There is a new way to do this that has many advantages -- use the Fortran 2003 ISO C Binding. This is a standard and therefore largely OS and language independent way of interfacing Fortran and C (and any language that will use C calling conventions). Intel Fortran 11 supports along with numerous other compilers -- not sure about version 10. Using the ISO C Binding, you can match any C name (any case), don't have to worry about underscores (and variations between compilers) and can specify the types and calling methods (by reference, by value) for the arguments. Intel provides some examples in a folder with their compiler; there are also examples in the gfortran manual and a discussion of additional considerations for Windows. There are previous questions & answers here and on the Intel Fortran forum.
I integrated C and Fortran about 20 years ago and maintained this integration up to 5 years ago. The tricks I used were:
I noticed that the Fortran compiler puts all symbols in uppercase, so make sure your C/C++ functions are written in uppercase as well. To verify how symbols are put in the .OBJ file, use DUMPBIN.
The Fortran compiler does not understand the name-mangling done by the C++ compiler. Compile all your C++ functions using the C style convention (using extern "C")
Arguments in Fortran are always put on the stack using references/pointers. Therefore, use pointer-arguments in your C function.
To be honest, I gave up integrating C and Fortran when I switched to VS2005, so things might have changed since then. Nevertheless, it's still a good idea to use DUMPBIN to see what kind of symbols the Fortran compiler produces, and adjust the compilation of C/C++ sources to fit with that.
We do it where I work.
Assuming you are using the Intel Fortran compiler, look up its docs. By default Intel Fortran passes everything by reference and (I believe) uses the C calling convention, with an all caps identifier. Strings are a particular issue, as Fortran likes to pass the length as a hidden parameter, with a compiler setting for where it goes in the parameter list.
A wise programer doesn't rely on defaults (where a mistake can lead to undefined behavior), and will use the intel INTERFACE statements to specify calling convention, parameter passing, and the link name for the routine. The information on this page (ATTRIBUTES Properties and Calling Conventions) is a must-read. In particular you need it to understand the arcane rules for when and where string length parameters will be passed. I have a printout of it that I keep on my person. :-)
One other thing to note is that versions of VisualStudio past 6 don't like mixed Fortran and C projects. We solved the problem by creating custom project files calling out to makefile, but that's a PITA. I'd suggest going with the flow and using separate projects unless you are doing this a lot like we are.
Solution found:
solution link
i have had several problem with linking, which could be solved with adding in project properties.
code for testing:
#include <stdio.h>
extern "C"
{
void f()
{
printf("hi from c\n mega test");
}
}
fortran code
PROGRAM HelloWorld
use, intrinsic :: iso_c_binding
implicit none
interface
subroutine f( ) bind( c )
use, intrinsic :: iso_c_binding
end subroutine f
end interface
call f
END PROGRAM HelloWorld
on demand i can upload the testproject. thanks all, hopefully it was my last problem with c and fortran
I was able to build obj from fortran sources thanks to the Custom Build Tools of Visual Express 2010. I guess it is also possible in Visual Studio.
If you want to mix C and Fortran together, there is a good tutorial here. It was written for gcc compilers but you should be able to learn how to deal with name mangling easily.
Depending on the compiler, compiled subroutines/functions are Uppercase/lowercase, with a trailing underscore, with a leading underscore,... For a succesfull linkage, you could use dumpbin tools to see how the name appears in the objectfile.
An other way is to use iso_c_binding modules, but it is available with Fortran 2003 only.
This is the how it works with gcc and console
c.c:
#include <stdio.h>
void f_()
{
printf("Hi from C\n");
}
fortran.f90
PROGRAM HelloWorld
CALL f
END PROGRAM HelloWorld
Makefile
SRCDIR=.
all: clean release run
release:
gcc -c c.c -o c.out
gfortran -c fortran.f90 -o fortran.out
gfortran -o out.exe fortran.out c.out
run:
out.exe
clean:
#$(ZSHMAGIC) rm -rf *.exe core* *.o a.out 2> /dev/null
One other question: have i always add '_' after c-function name, which i use in the fortran program?

Cygwin gcc compiled fails in IDE complaining about 'exit' undeclared

When I compile a program using just
gcc code.c
There are no messages, and an output file is generated successfully. The outputted file works. However, when I try to the same cygwin installation's gcc compiler in an IDE (I've tried Netbeans and Dev-C++), I get the following errors
main.cpp:27: error: `exit' undeclared (first use this function)
main.cpp:27: error: (Each undeclared identifier is reported only once for each function it appears in.)
main.cpp:77: error: `write' undeclared (first use this function)
main.cpp:78: error: `close' undeclared (first use this function)
I don't see what's different. Why does it not compile?
OK, the issue was that in the IDE, the file had a .cpp extension, whereas when I was compiling from a terminal, it had a .c extension. So, my new question is why does it not compile when it's treated as a c++ file. Isn't C a subset of C++?
C++ is stricter then C. Where C allows you to call a function without a prototype, C++ does not allow this.
To solve the problem, you want to add:
#include <stdlib.h>
Also, when compiling at the command line. Make sure to use the -Wall flag so you'll get important warnings:
gcc -Wall code.c
The IDE is using fussier options to the compiler. You need to include some headers:
#include <stdlib.h> // exit()
#include <unistd.h> // close(), write()
The default options allow almost anything that might be C to compile. By the looks of it, the IDE sets '-Wmissing-prototypes' as one of the compiler options.
If you compile code with a C++ compiler, you must ensure that all functions are declared before use. C is sloppier (or can be sloppier) about that - it is recommended practice to ensure all functions are declared before being defined or referenced, but it is not mandatory. In C++ it is not optional.
There is a subset of C that is also a subset of C++; there are bits of C that are not C++, and there are many bits of C++ that are not C. In particular, an arbitrary C program is not, in general, a C++ program. For example, a C program may not declare 'exit()' and yet it can both use it and still compile. A C++ program must declare 'exit()' before it can user it and compile.
You will have to use g++ for compiling .cpp files.
One possible reason may be that the IDE is unable to access the include files, the cygwin gcc compiler may be expecting it in /usr/include(not sure), and the dev-cpp may not be able to access it.