Skip to content

Commit f896044

Browse files
authored
Tests of cross compiling:
g++ library for gfortran
1 parent 4b4bf9c commit f896044

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Diff for: cross_compile.md

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
##
2+
- Ref:https://stackoverflow.com/questions/47957255/cmake-linking-fortran-against-static-c-library-fails
3+
- ex.c
4+
```
5+
int get_key()
6+
{
7+
return 10000;
8+
}
9+
```
10+
- ex1.c
11+
```
12+
int get_key1()
13+
{
14+
return 10001;
15+
}
16+
```
17+
- ex.f08
18+
```
19+
program main
20+
implicit none
21+
22+
interface
23+
function get_key() bind(c, name='get_key')
24+
use iso_c_binding
25+
integer(kind=c_int) :: get_key
26+
end function get_key
27+
end interface
28+
29+
write(*, '(i0)') get_key()
30+
end program main
31+
```
32+
- For c + fortran
33+
```
34+
gcc -c ex.c
35+
gcc -c ex1.c
36+
ar cr libex.a ex.o ex1.o
37+
gfortran fex.f08 -L. -lex
38+
```
39+
- For C++ + fortran
40+
```
41+
g++ -c ex.c
42+
g++ -c ex1.c
43+
ar cr libex.a ex.o ex1.o
44+
gfortran fex.f08 -L. -lex
45+
```
46+
- This yields `undefined reference to 'get_key'`
47+
- Add `extern "C"` to ex.c and ex1.c. Then repeat the process
48+
```
49+
extern "C" int get_key()
50+
{
51+
return 10000;
52+
}
53+
```
54+
- If `extern "C"` is not used, then use -static with g++ command
55+
```
56+
g++ -static -c ex.c
57+
g++ -static -c ex1.c
58+
ar cr libex.a ex.o ex1.o
59+
gfortran fex.f08 -L. -lex
60+
```
61+
62+
# In cmake, adjusting archive options
63+
SET(CMAKE_C_ARCHIVE_CREATE "<CMAKE_AR> <LINK_FLAGS> cr <TARGET> <OBJECTS>")
64+
SET(CMAKE_C_ARCHIVE_APPEND "<CMAKE_AR> <LINK_FLAGS> r <TARGET> <OBJECTS>")
65+
SET(CMAKE_CXX_ARCHIVE_CREATE "<CMAKE_AR> <LINK_FLAGS> cr <TARGET> <OBJECTS>")
66+
SET(CMAKE_CXX_ARCHIVE_APPEND "<CMAKE_AR> <LINK_FLAGS> r <TARGET> <OBJECTS>")

0 commit comments

Comments
 (0)