Python and C++ Together

Chapter 14 · Tamil Nadu State Board

  • 6 min read
  • 6-question quiz

Every key point below shows the sentence from your textbook it comes from. Book back answers are solved and checked against the book; answers we could not prove are left out. How we check content

In short

This lesson explains how Python can work with C++ by wrapping C++ programs and running them through a Python script. It introduces scripting languages, MinGW, and the Python modules used to process command-line arguments and compile and execute C++ files. A palindrome example shows how the steps fit together, and a faulty C++ program demonstrates that compilation errors can be displayed. These ideas help students connect programs written in two languages and organize code into reusable modules.

Written by AI from this lesson. How we check it

Key points

  • Wrapping means importing a C++ program into a Python program.
    From your textbook
    “Importing C++ program in a Python program is called wrapping up of C++ in Python.”
  • A scripting language is designed to connect and communicate with other programming languages.
    From your textbook
    “A scripting language is a programming language designed for integrating and communicating with other programming languages.”
  • MinGW provides runtime header files for compiling and linking C, C++ and FORTRAN code for Windows.
    From your textbook
    “MinGW refers to a set of runtime header files, used in compiling and linking the code of C, C++ and FORTRAN”
  • Python modules divide code into manageable parts and allow functions to be reused.
    From your textbook
    “We use modules to break down large programs into small manageable and organized program.”
  • The sys module's argv list holds the arguments passed to a Python program from the command line.
    From your textbook
    “sys.argv is the list of command-line arguments passed to the Python program.”
  • The os module can run a command in the operating system shell, including a command to compile C++ code.
    From your textbook
    “os.system(): Execute the C++ compiling command (a string contains Unix, C command which also supports C++ command) in the shell”
  • The getopt module splits command-line options and arguments, while compilation errors can be displayed during execution.
    From your textbook
    “The getopt module of Python helps you to parse (split) command-line options and arguments.”
Test yourself: 6 questions

Python and C++ Together

Python and C++

PythonC++
Typically interpretedTypically compiled
Dynamically typedStatically typed
A variable does not need a declared data typeA variable needs a declared data type
Can be used as a scripting language and a general-purpose languageA general-purpose language

Python can act as a top-level program that calls routines written in C or C++. This is useful when existing C++ logic needs to be called or controlled through Python.

Definition

Wrapping
Wrapping is importing a C++ program into a Python program by creating a Python interface for the C++ program.

Scripting Languages

Definition

Scripting language
A scripting language is designed to integrate and communicate with other programming languages.

Scripting languages are interpreted and do not require a compilation step. A scripting language needs an interpreter, while a programming language needs a compiler. A language may be called scripting or programming depending on the environment where it is used.

Uses of scripting languages

  • Automating tasks in a program
  • Extracting information from a data set
  • Writing less code than with traditional programming languages
  • Adding functions to applications and connecting complex systems

Python is an interpreted, high-level, general-purpose programming language. It can process text, numbers, images and scientific data on modern computer operating systems.

Python Features and Wrapping Tools

Python features compared with C++

  • Python uses Automatic Garbage Collection; C++ does not.
  • Python is dynamically typed; C++ is statically typed.
  • Python runs through an interpreter; C++ is pre-compiled.
  • Python code tends to be 5 to 10 times shorter than C++ code.
  • Python does not need explicit type declarations; C++ does.
  • A Python function can accept an argument of any type and return multiple values without prior declarations. A C++ return statement can return only one value.

Definition

Garbage Collection
Garbage Collection is the process by which Python frees and reclaims memory blocks that are no longer in use.

Interfaces used to wrap C++ programs in Python

  • Python-C-API
  • Ctypes
  • SWIG
  • Cython
  • Boost. Python
  • MinGW

Definition

MinGW
MinGW is a set of runtime header files used to compile and link C, C++ and FORTRAN code for the Windows Operating System.

MinGW allows a C++ program to be compiled and executed dynamically through Python using g++. The g++ program calls GCC and links the required C++ library files to the object code.

Executing a C++ Program Through Python

Use a command prompt or run terminal to execute the Python program. Use the cd command to change to the directory containing the program files.

Execution syntax

Python <filename.py> -i <C++ filename without cpp extension>

Python runs the Python program; <filename.py> is its name; -i indicates input mode; the final name identifies the C++ file without its cpp extension.

Worked example

Run pycpp.py with the C++ program pali.

Try it first, then show the solution
  1. In the command prompt, enter Python pycpp.py –i pali.
  2. The C++ filename is given as pali, without the .cpp extension.
  3. If the programs are in different folders, specify the complete path for the files.

Answer: The command compiles and executes the C++ program through Python. If compilation succeeds, the program displays its output; otherwise, an error is displayed.

In the example, the input 232 is reported as a palindrome because its reverse is 232. The input 234 is not a palindrome because its reverse is 432. Use the cls command to clear the command window.

Remember: Give the C++ filename without its .cpp extension in the execution command.

Running a C++ program through Python

A Python script can take a C++ file name from the command line. It adds .cpp to make the input file name and .exe to make the executable file name. Then it uses g++ to compile the C++ file and runs the executable.

How the Python script works

  • sys.argv[1:] passes the command-line arguments to main(), without the Python program name.
  • getopt.getopt(argv, "i:") splits the arguments into options and other arguments. The option list contains the mode and file path. If there is no error, args is an empty list.
  • The for loop unpacks each option tuple. o holds the mode, and a holds the C++ file path.
  • run(a) adds the file extensions, calls g++ through os.system(), and then asks os.system() to execute the .exe file.

Worked example

The Python program is run with -i c:\pyprg\pali_cpp. The C++ program accepts 56765. What output does the example show?

Try it first, then show the solution
  1. The Python script compiles and runs the C++ file.
  2. The reverse of 56765 is 56765.
  3. The original number and its reverse are the same.

Answer: The output says, “The number is a palindrome”.

Worked example

The Python program is run with -i c:\pyprg\pali_cpp. The C++ program accepts 56756. What output does the example show?

Try it first, then show the solution
  1. The Python script compiles and runs the C++ file.
  2. The reverse of 56756 is 65765.
  3. The original number and its reverse are different.

Answer: The output says, “The number is not a palindrome”.

Remember: The Python script prepares the file names, runs g++ to compile the C++ program, and uses os.system() to run the executable.

Displaying C++ compilation errors

Python can show errors produced when g++ compiles a C++ program. In the example, the statement std::cout<<"hello" is missing a semicolon before return 0;. The compiler displays the error and its line number.

Because compilation fails, the executable is not available to run. The later attempt to run the .exe file produces a message saying it is not recognized as a command.

Remember: A compiler error is shown with the line number counted from the beginning of the C++ program.

Python, C++, modules, and scripting

C++ and Python

C++Python
Compiler based languageInterpreter based language
Compiled staticallyInterpreted dynamically
The programmer explicitly gives data types.The data type does not need to be given explicitly; Python handles a variable based on its value.

Definition

Scripting language
A programming language designed for integrating and communicating with other programming languages.

Definition

MinGW
A set of runtime header files used to compile and link C, C++ and FORTRAN code to run on Windows Operating System.

Modules and related terms

  • The dot (.) operator accesses functions of an imported module.
  • The sys module provides access to some interpreter variables and functions that interact with the interpreter.
  • The OS module provides a way to use operating system dependent functionality.
  • The getopt module parses command-line options and arguments.

Questions students ask

Short, direct answers to what students search for in this chapter.

What is wrapping in Python?

Wrapping is importing a C++ program into a Python program by creating a Python interface for it. This lets the Python program call or use the C++ program.

What is a scripting language?

A scripting language is designed to integrate and communicate with other programming languages. It is interpreted and does not require a compilation step. It needs an interpreter to run.

What is Garbage Collection in Python?

Garbage Collection is the process by which Python periodically frees and reclaims blocks of memory that are no longer in use. It helps free memory occupied by unwanted objects.

How do I run a C++ program through Python?

Use the command syntax Python <filename.py> -i <C++ filename without cpp extension>. The Python filename identifies the Python program, and -i indicates input mode. Give the C++ filename without the .cpp extension.

What is MinGW used for?

MinGW provides runtime header files used to compile and link C, C++ and FORTRAN code for the Windows Operating System. It allows C++ programs to be compiled and executed dynamically through Python using g++.

What is a Python module?

A Python module is a file containing Python statements and definitions. Modules split large programs into smaller, organised parts. They also allow commonly used functions to be imported and reused instead of copied into different programs.

Show 9 more questions

How do you call a function from an imported Python module?

First import the module using the import keyword. Then use the dot operator between the module name and function name. For example, after importing factorial, call its function with factorial.fact(5).

What does sys.argv contain?

sys.argv is a list of command-line arguments passed to a Python program. sys.argv[0] contains the Python program name. sys.argv[1] contains the next argument, such as the C++ file passed to the program.

What does os.system() do in the C++ example?

os.system() runs a command string in the operating system's shell. The example joins the g++ compiler command, the C++ file name, the -o output option, and the executable file name into one string.

What do opts and args contain after getopt.getopt()?

opts contains the parsed options and their values, such as the input option and C++ file path. args contains leftover arguments. When there are no leftover arguments, args is an empty list, shown as [].

How does Python run a C++ program?

Python reads the command-line option and C++ file path. The script adds .cpp and .exe to form the file names, then calls g++ through os.system() to compile the C++ file. It uses os.system() again to run the executable.

What does getopt.getopt() do in Python?

getopt.getopt() parses or splits command-line options and arguments. In the example, it separates the mode and C++ file path into an option tuple. If there is no error, the other-arguments list, args, is empty.

How does Python show errors in a C++ program?

The Python script calls g++ to compile the C++ program. If the C++ code has an error, the compiler displays the error and its line number. If compilation fails, the executable may not exist, so trying to run it can also produce a command error.

What is the difference between C++ and Python data types?

C++ is described as statically compiled, and the programmer must explicitly state the data type for each data value. Python is dynamically interpreted, so the programmer does not need to give the data type explicitly. Python handles a variable based on the type of value.

What are the uses of the sys, OS, and getopt modules?

The sys module provides access to some interpreter variables and functions. The OS module provides operating system dependent functionality. The getopt module parses command-line options and arguments.

Book back answers

22 textbook exercises, solved and checked against the book. Questions we could not prove are left out.

Choose the best answer (1 Mark)

  1. Which of the following is not a scripting language?

    • (A) JavaScript
    • (B) PHP
    • (C) Perl
    • (D) HTML
    Try it, then show the answer

    (D) HTML

    The chapter lists JavaScript, PHP and Perl as scripting languages, but does not list HTML as one.

    From the book: “Some of the most widely used scripting languages are JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl.”

  2. Importing C++ program in a Python program is called

    • (A) wrapping
    • (B) Downloading
    • (C) Interconnecting
    • (D) Parsing
    Try it, then show the answer

    (A) wrapping

    The chapter names importing a C++ program in Python as wrapping up C++ in Python.

    From the book: “Importing C++ program in a Python program is called wrapping up of C++ in Python.”

  3. The expansion of API is

    • (A) Application Programming Interpreter
    • (B) Application Programming Interface
    • (C) Application Performing Interface
    • (D) Application Programming Interlink
    Try it, then show the answer

    (B) Application Programming Interface

    The chapter explicitly gives this expansion for API.

    From the book: “Python-C-API (API-Application Programming Interface for interfacing with C programs)”

  4. A framework for interfacing Python and C++ is

    • (A) Ctypes
    • (B) SWIG
    • (C) Cython
    • (D) Boost
    Try it, then show the answer

    (D) Boost

    The chapter identifies Boost.Python as a framework for interfacing Python and C++.

    From the book: “Boost. Python (a framework for interfacing Python and C++)”

All 22 book back answers →

Practice

Question 1 of 6Score 0

What does wrapping mean in this lesson?

Exam questions

Practice questions with model answers. These are not from an official paper.

What is wrapping in the context of Python and C++?2 marks

Wrapping is importing a C++ program into a Python program, allowing the Python program to work with C++ code.

State two uses of Python modules.2 marks

Modules help split large programs into smaller, manageable parts. They also allow commonly used functions to be reused by importing them instead of copying their definitions.

What are the roles of sys.argv and getopt in the example program?2 marks

sys.argv holds the command-line arguments passed to the Python program. getopt parses those arguments into options and remaining arguments.

Explain how the Python script compiles and runs a C++ file using MinGW.5 marks

The script reads the C++ file path from the command-line input and uses os.system() to run g++, which compiles the file and sends the executable to an output file. The script then uses os.system() again to execute that file.

Watch out

  • Do not confuse argv[0], which contains the Python program name, with argv[1], which holds the next command-line argument.
  • Do not assume getopt() puts all parsed values in args: the lesson says parsed options are stored in opts, while args is empty when there is no error.

Still stuck on this lesson?

Get an AI answer grounded in your actual textbook — with the exact page reference.

Ask AI about this topic →