3

I am writing a C++ program that uses sockets. I want my program to run on both Windows and Linux.

  • On Windows, I need to use:

Winsock2.h

  • On Linux, I need to use:

arpa/inet.h

How can I define my C++ program to run on different platforms, and how to include <arpa/inet.h> while I use Visual Studio on Windows?

Please give me an example!

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    You cant make a single program executable that runs on multiple platforms. You need to make separate executables for each platform. You can create multiple projects and share source code between them. Or use a compiler that can output executables for multiple platforms from a single project (Visual Studio on Windows can't make Linux executables). But either way, you need to use `#ifdef`/`#ifndef` statements to wrap platform-specific code, such as `#include` statements. Most compilers define values that can be checked for to identify which platform is being compiled for. – Remy Lebeau Mar 03 '18 at 16:54
  • You may be interested to know that there is a [Networking TS](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4711.pdf) nearing publication, although it may be a while before your favorite standard library implementations support it. – Davis Herring Mar 03 '18 at 20:15
  • And while you wait for networking to be added to the next C++ standard, you can use Boost::Asio on which it is based. See http://www.boost.org . Asio support Win32, Linux and several other others so you can easily write an application that runs cross-platform with a single code base. – stanthomas Mar 05 '18 at 01:44

0 Answers0