Calling Fortran code from C++ on Visual Studio 2015

Here I describe a little on how to call Fortran code from C++ using Visual Studio. I will be focusing on MinGW gfortran as that is a popular free Fortran compiler on Windows platform.

System Requirements:

  • Visual Studio 2015 (C++) (I am using the free community version)
  • MinGW gfortran (64bit, using the one from Msys here)

My Fortran code is just a simple function in a module:

module testfor
    use, intrinsic :: iso_c_binding
    implicit none
contains
    subroutine testingfor(x) bind(c, name="testingfor")
        implicit none
        double precision, intent(in) :: x

        print *, "# calling testfor in Fortran!!"
        print *, "x = ", x 
    end subroutine
end module testfor

Note that I am using Fortran 2003 standard “iso_c_binding”. The “bind” syntax allow you to customize the function name to be called in C++. Here I use the same name “testingfor”. If you are using the old (pre-2003) style, the naming convention for a function in a module may be a little complicated. Anyway, that helps us clean up the code a little.

Next, my C++ main function is very simple as well:

extern "C" {
	void testingfor(double* x);
}

int main(int argc, char* argv[]) {
	double y = 1.0;

	testingfor(&y);
}

The “extern C” syntax acts as an interface. Note that the input argument for the Fortran function must be a pointer as Fortran is pass-by-reference only.

Here is the main dish! In Windows, we need the “import” library (.lib) and dynamic library (.dll). To get these files, we need to the following steps:

gfortran -c testfor.f90

dllwrap.exe --export-all-symbols testfor.o -lgfortran --output-def testfor.def -o testfor.dll

lib.exe /machine:x64 /def:testfor.def

First command is simply compiling our Fortran module into an object file. Second command creates the definition file (.def) and the dll file (.dll). The dllwrap.exe comes with MinGW as for as I know. It may complain with the following error:

dllwrap.exe: no export definition file provided.
Creating one, but that may not be what you want

But I think we can ignore it.. The last line with lib.exe earlier is to create the import lib with the def file. Now we have what we need, the testfor.lib and testfor.dll.

Now we need to go into Visual Studio to set up. I don’t go over Visual Studio here. What we need to do is simply add the testfor.lib in the resource folder and let VS know you need it to compile. The last step can be done by adding “testfor.lib” into Project-> Properties-> Configuration Properties-> Linker-> Input-> Additional Dependencies. Remember the resultant exe file do require the testfor.dll in the path in order to run. Here is the result:

Hopefully this is useful.

Reference: http://www.cs.cmu.edu/~barbic/arpack.html

55 thoughts on “Calling Fortran code from C++ on Visual Studio 2015

  1. C++ is a powerful programming language with many benefits, including:

    High performance: C++ is a compiled language, which means it can be optimized for high performance. It’s often used for developing software that requires fast execution, such as video games, operating systems, and scientific simulations.

    Object-oriented programming: C++ supports object-oriented programming, which allows developers to create modular, reusable code. This makes it easier to write and maintain complex programs.

    Platform independence: C++ can be compiled to run on multiple platforms, including Windows, Mac, and Linux. This makes it a popular choice for developing cross-platform software houses for sale in Lebanon.

    Memory management: C++ gives developers low-level access to memory management, which allows for more efficient memory usage. However, this requires careful coding practices to avoid memory leaks and other issues.

  2. There are different coding language C++ ,html,css theses languages are to code different project i am using html for my client site bestpicsart which is about photo and video editing ,about fonts, stickers ,blogs how to take photos and how to edit the

  3. SMM Panel One is your one-stop solution for skyrocketing your social media presence and success. With our cutting-edge Social Media Marketing (SMM) panel, you can harness the power of various platforms to elevate your brand, engage your audience, and drive unprecedented growth. From increasing followers, likes, and comments to generating buzz around your content, our platform offers a seamless and efficient way to conquer the digital landscape. Boost your social media game with SMM Panel One and witness the magic of organic reach and genuine interactions like never before!

  4. In the dynamic world of social media, an SMM panel is your secret weapon. These panel streamline marketing efforts, offering services like likes, followers, and engagement to boost your online presence. With an smm panel you can effortlessly navigate the ever-changing landscape of social success.

  5. Are you looking to supercharge your social media marketing? Discover the power of smm panel services at SMMPanel2.com. Elevate your online presence with cost-effective solutions for likes, followers, and engagement. Explore the endless possibilities of SMM to transform your brand and business today!

  6. No. 1 in Asia and has been trusted by people who come to use the service whether Thai or foreigner and we also have Admin will gradually provide services to play online casinos with us.
    ติดต่อ 123

  7. Loft Thai Spa: Thai Herbal Hair Mask for Nourishment and Shine Nourish and enhance the beauty of your hair with Loft Thai Spa’s Thai Herbal Hair Mask. Our skilled therapists apply a blend of traditional Thai herbs and natural ingredients to promote hair health, nourish the scalp, and restore shine. Feel the rejuvenating touch and herbal infusion as your hair is pampered, leaving you with silky, lustrous locks. Experience the transformative power of Thai herbal hair mask at Loft Thai Spa.

  8. PimAccounting: Cybersecurity Financial Services Cybersecurity is a top priority in today’s digital landscape. PimAccounting offers specialized financial services to cybersecurity firms and tech companies. We assist with budgeting for security solutions, cyber insurance analysis, and cost-benefit assessments. Our team understands the critical role of cybersecurity in protecting your business and financial assets. Partner with PimAccounting to strengthen your cybersecurity defenses while optimizing financial resources. Trust us to be your financial partner, delivering insights that empower your organization to thrive securely in an interconnected world.

  9. Drive User Activation with PimClick’s Onboarding Emails User activation is vital for app success, and PimClick designs effective onboarding e-mails that activate users. PimClick delivers personalized onboarding messages, guides users through key features, and encourages first actions. Drive user activation with PimClick’s onboarding e-mails, ensuring that new users experience the full value of your app and become loyal, engaged users who drive app growth and success.

  10. Drive User Activation with PimClick’s Onboarding Emails User activation is vital for app success, and PimClick designs effective onboarding e-mails that activate users. PimClick delivers personalized onboarding messages, guides users through key features, and encourages first actions. Drive user activation with PimClick’s onboarding e-mails, ensuring that new users experience the full value of your app and become loyal, engaged users who drive app growth and success.

  11. Spa-Awards – The Journey to Crystal Reiki Healing Crystal Reiki healing combines the healing powers of crystals with Reiki energy work for balance and rejuvenation. Spa-Awards celebrates spas that offer Crystal Reiki healing experiences, inviting guests on a transformative journey of energetic renewal. By embracing Crystal Reiki healing, we recognize the transformative effects of crystals and Reiki in promoting physical, emotional, and spiritual well-being. Experience the journey of Crystal Reiki healing at the Spa-Awards celebrated spas, where energy and relaxation merge in harmonic resonance.

  12. Laundry Bangkok: Travel Laundry Essentials Traveling light? Laundry Bangkok offers travel laundry essentials, including stain removers and wrinkle-releasing sprays, to keep your clothes fresh and tidy on the go. Experience the convenience and efficiency of our travel laundry essentials. Trust us to make your travels seamless and organized with Laundry Bangkok.

  13. 🍧เว็บไซต์คาสิโนสดยอดนิยมสำหรับการพนัน เพราะนอกจากความพิเศษของเกมที่มีให้เลือกมากมายแล้ว ยังมีโปรโมชั่นให้กับลูกค้าอีกมากมาย คลิกสมัคร ▶▶บาคาร่า

  14. Great post! For unparalleled market insights and research resources tailored specifically to the market research industry, explore Stats N Data (https://www.statsndata.org). Our platform offers invaluable market intelligence across diverse domains, empowering businesses with actionable insights that drive success. Looking forward to more engaging content from you!

  15. บาคาร่าเว็บตรง ไม่ผ่านเอเย่นต์ ให้บริการเกมสล็อตและบาคาร่า แตกง่าย แตกบ่อยe6trey
    บาคาร่า

  16. Any business looking to elevate its social media game should definitely consider SMM Panel 2. Their genuine SMM Panel solutions have helped me tremendously in growing my audience and engagement across Instagram, Facebook, LinkedIn, and more. Can’t recommend their services enough!

  17. Laundry Bangkok: Travel Laundry Essentials Traveling light? Laundry Bangkok offers travel laundry essentials, including stain removers and wrinkle-releasing sprays, to keep your clothes fresh and tidy on the go. Experience the convenience and efficiency of our travel laundry essentials. Trust us to make your travels seamless and organized with Laundry Bangkok.เว็บเกมสล็อต

  18. I just learned about Smm panel amazing services, and I have to mention that they have the best Smm Panel out there. Their remarkable outcomes demonstrate their proficiency in the Indian social media marketing landscape. Smmpanel is your best option if you’re a worldwide brand trying to reach the Indian market or an Indian company wishing to improve its online visibility.

Leave a Reply

Your email address will not be published. Required fields are marked *