Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is LeetCode able to compile a C++ program without me writing a 'main()' function?

As far as I know, a C++ compiler looks for a function called main() in order to know where the program should start.

But when I use the LeetCode site, the expected solution's code has no main function. For example:

class Solution {
public:
    int foo(string s) {
        int ans = 0;
        // <work>
        return ans;
    }
 };

It seems like the program starts from whatever function is first in the public section of the Solution class. How did LeetCode's compiler decide that?

like image 378
Shivani Avatar asked Sep 02 '25 01:09

Shivani


2 Answers

Every C++ program requires a int main() or int main(int argc, char** argv) function*. Without main() you can't produce executable program that can be run.

What does LeetCode do then? It compiles the code you provide together with a main() function and test cases, which you don't see. It then executes that program, analyses test results and provides you with score. Your code is only a part of the entire program that LeetCode compiles.


* An exception is compiling for platforms without an operating system, e.g., a tiny embedded CPU that can't even hold a proper OS. Is it possible to write a program without using the main() function?

like image 110
Yksisarvinen Avatar answered Sep 05 '25 04:09

Yksisarvinen


Some online coding platforms, like LeetCode and GeeksforGeeks (GFG), doesn't expose their main functions anymore. This was mostly done because the main function becomes very repetitive for every question. Also, people used to optimize input output, cache test cases for getting better execution time in contests, etc.

Now back to the question. LeetCode just inserts your code into their driver code. If you create another main function, the compiler will complain about a previous declaration.

Enter image description here

As you can see, the actual main function starts from the line 21 in this example.

With some Python magic you can actually see the entire code. (I am not a C++ person, so I couldn't get this done using C++).

Here's the code to fetch the current file content. (Note this is the two sums problem)

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        return []


def print_current_file():
    current_file_path = __file__
    with open(current_file_path, 'r') as file:
        file_contents = file.read()

    print(file_contents)
print_current_file()

Output:

# Coding: utf-8
from string import *
from re import *
from datetime import *
from collections import *
from heapq import *
from bisect import *
from copy import *
from math import *
from random import *
from statistics import *
from itertools import *
from functools import *
from operator import *
from io import *
from sys import *
from json import *
from builtins import *

import string
import re
import datetime
import collections
import heapq
import bisect
import copy
import math
import random
import statistics
import itertools
import functools
import operator
import io
import sys
import json

import precompiled.__settings__
from precompiled.__deserializer__ import __Deserializer__
from precompiled.__deserializer__ import DeserializeError
from precompiled.__serializer__ import __Serializer__
from precompiled.__utils__ import __Utils__
from precompiled.listnode import ListNode
from precompiled.nestedinteger import NestedInteger
from precompiled.treenode import TreeNode

from typing import *

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

# User-submitted code insert below
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        return []


def print_current_file():
    current_file_path = __file__
    with open(current_file_path, 'r') as file:
        file_contents = file.read()

    print(file_contents)
print_current_file()

import sys
import os
import ujson as json

def _driver():

    des = __Deserializer__()
    ser = __Serializer__()
    SEPARATOR = "\x1b\x09\x1d"
    f = open("user.out", "wb", 0)
    lines = __Utils__().read_lines()

    while True:
        line = next(lines, None)
        if line == None:
            break
        param_1 = des._deserialize(line, 'integer[]')

        line = next(lines, None)
        if line == None:
            raise Exception("Testcase does not have enough input arguments. Expected argument 'target'")
        param_2 = des._deserialize(line, 'integer')

        ret = Solution().twoSum(param_1, param_2)
        try:
            out = ser._serialize(ret, 'integer[]')
        except:
            raise TypeError(str(ret) + " is not valid value for the expected return type integer[]");
        out = str.encode(out + '\n')
        f.write(out)
        sys.stdout.write(SEPARATOR)


if __name__ == '__main__':
    _driver()

As you can see, the user code gets inserted after the # user submitted code insert below line.

like image 21
Julkar9 Avatar answered Sep 05 '25 06:09

Julkar9