C/C++, C#, JAVA (Part 1): Introduction to Code Templates and Library Code

2020年3月22日 44点热度 0人点赞 0条评论
内容目录

Default Code Template

In compiled high-level programming languages, almost every language has a static main method as the entry point for program execution, and each language has its own coding conventions. To learn C/C++, C#, and JAVA, we should start by exploring the default code templates step by step.

Convention:
We often see the terms function and method being used interchangeably by many people.
A method is in the form of void Test(){};
A function refers to a code block with a defined name that can be called by its name, attributes, fields, methods, delegates, events, etc.;
Any code block that can be called or used with a definite name is a function; while a method is a code block composed of return value, name, parameters, etc.;

C/C++ and Java primarily use Camel-Case naming, while C# uses Pascal Case.
Since the article contains many code snippets and examples, naming may not strictly follow the conventions of the language (mainly due to the author's habit of writing in C#).

Code Templates

C

#include <stdio.h>

int main()
{
    /* code */
    return 0;
}

C++

#include <iostream>
using namespace std;

int main()
{
    /* code */
    return 0;
}

C#

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            /* code */
        }
    }
}

JAVA

package com.company;
import com.company.test.*;

public class Main {
    
    public static void main(String[] args) {
        Test test = new Test();
    }
}

Both C# and Java have a static entry point for the main method.
The main method in C# is capitalized, while in other languages it is lowercase.

Importing and Parsing Library Code

In every programming language, there are a large number of official library codes and custom library codes, such as SDKs, so how should we import and use them?

C

C language source files end with .c or .h, where .h is generally used to define members, and .c is used to implement members.
.c is called a source file, and .h is called a header file.

In C language, we use #include "{file_name}.{.c|.h}" or #include <{file_name}.{.c|.h}> to use system or custom library codes.
In simple terms, #include <> is used for system-provided code, while #include "" is for your own code or third-party code.
Reference: http://c.biancheng.net/view/443.html

When writing code and compiling, there is no direct connection between .c and .h files and the code within them.

C language does not have interfaces (object-oriented), so to achieve decoupling, it separates the definition and implementation of functions into two parts. The .h file defines the members that can be accessed externally and how to call these members. The .c file implements the members declared in the .h file.

So, how do we declare and implement functions in .h and .c files for external use?

Implementing .h, .c, and External Calls

Create a Test.h file.
This file declares a getA method, which does not require input parameters and returns an int type value.
The extern keyword indicates that this method can be called externally.

#include <stdio.h>

extern int getA(void);

Now we use this method in the main function.

#include <stdio.h>
#include "Test.h"

int main() {
    int a = getA();
    printf("%d", a);
    return 0;
}

Next, we implement Test.c.

#include <stdio.h>

// Implementing getA method
int getA(void) {
    return 666;
}

The above code outlines the writing method for .h and .c files as well as the provision for external calls.

.h and .c Files

As mentioned earlier, .h and .c files do not have an inherent connection. Let me explain.

Because .h and .c are not like interfaces and inheritance in C# and JAVA, there are no strict regulations. Therefore, you can write only a .h file or a .c file.
The .h file can also implement code, for example, the Test.h file:

#include <stdio.h>
extern int getA(void) {
    return 666;
}

The C language compilation involves four steps: preprocessing, compilation, assembly, and linking.

  • Preprocessing: Conditional compilation, macro definition handling, etc.
  • Compilation: Checking syntax, generating assembly.
  • Assembly: Converting assembly code to machine code.
  • Linking: Combining with other components to generate an executable file.

Reference:
http://c.biancheng.net/view/1736.html
https://blog.51cto.com/7905648/1297255

The real "connection" between .h and .c files only occurs in the final linking stage.
Reference: https://www.cnblogs.com/laojie4321/archive/2012/03/30/2425015.html

C++

It is said that Bjarne Stroustrup, the father of C++, never fully understood C++ as a programming language.

C++ source files have the extension .cpp.

In C++, we see #include <iostream>; why isn’t it with .h or .c?
C++ is a superset of the C language, implementing object-oriented features, and it introduced the concept of namespaces and libraries.
In C++, #include <stdio.h> is the typical header file inclusion method, while #include <iostream> is the inclusion for C++ libraries, specifically referring to the standard library.

The C++ standard library is divided into two parts:

  • Standard function library: Inherits from the C language and consists of functions that do not belong to classes.
  • Object-oriented class library: A collection of classes and their related functions.

Namespaces

Earlier we saw using namespace std; in the C++ code template, which is used to import a namespace.

In C++, functions declared in .h can also be implemented directly, but doing so does not allow one to experience the advantages of object-oriented programming.

C++ uses an object-oriented approach, employing the structure of namespace-class-member for writing code, as shown below.
Let's write Test.h.

namespace first_space {
    int func();
}

Now let's write Test.cpp.

namespace first_space {
    int func() {
        return 666;
    }
}

In the main function, we call it as follows.

#include <iostream>
#include "Test.h"

using namespace std;
using namespace first_space;

int main()
{
    int a = func(); // first_space
    cout << a << endl;
    return 0;
}

As you can see, the namespace simply adds a scope limit.
In C++, functions can be defined within classes, namespaces, or directly written in the source file.

C#

C# is my favorite language, hehe.
In C#, after the class library is compiled, it becomes a .dll file.

Here is an example of C# namespace and how to reference a namespace.

namespace ConsoleApp1
{
    using Test;
    class Program
    {
        static void Main(string[] args)
        {
            T666 t = new T666();
            t.Test();
        }
    }
}

namespace Test
{
    public class T666
    {
        public void Test() {}
    }
}

In C#, there are no strict requirements for namespaces.
Generally, the namespace is composed of [ProjectName].[DirectoryName].[DirectoryName]....
It starts with the project name, and each subsequent directory name is concatenated.
For example, if you want to implement user identity authentication functionality and place this code in the MyProj/Auth directory, then the namespace would be MyProj.Auth.
C# source files have the extension .cs and generally, an independent function class or interface uses a single .cs file.
However, this is not mandatory in C#. You will gradually learn this as you study C#. The namespace structure is largely similar to C++.

In C#, the namespace acts as a scope limit for class usage.
The minimum granularity of calling is for classes, structs, enums, etc.
All fields, properties, methods, etc., must be defined and implemented within a class.

Upon importing a namespace in C#, you can use all the classes within that namespace.

Java

Java has quite a few more rules.
Java source files end with .java.
Each .java file can only contain one public class, and the class name must match the name of the .java file.
Java does not use namespaces but utilizes packages, and the package name is strictly set based on directory names.

In Java, the import keyword is used to import packages, such as import java.io.*;.
There are two forms of import, one is to import a specific class name.

import java.io.PrintStream;

After that, you can use the PrintStream class.
The other way is to use import java.io.*; which allows you to use all classes under that package.

In Java, the standard library begins with java. or javax..

If you wish to make a class available for external use, you need to use the package keyword.

Here's an example.

The directory structure of the program is as follows:

.
│  main
│
└─com
    └─company
        │  Main.java
        │  MyFrame.java
        │
        └─test
                Test.java
                Test2.java

We write two classes, Test and Test2.

# Test
package com.company.test;

public class Test {
    public void My() {
        Test2 t = new Test2();
    }
}

# Test2
package com.company.test;

public class Test2 {
}

In the main function, we call it as follows.

package com.company;
import com.company.test.*;

public class Main {
    public static void main(String[] args) {
        Test test = new Test();
    }
}

痴者工良

高级程序员劝退师

文章评论