How to Define Module in Verilog: Syntax and Example
In Verilog, a
module is defined using the module keyword followed by the module name and port list in parentheses. The module body contains declarations and statements, and it ends with the endmodule keyword.Syntax
The basic syntax to define a module in Verilog is:
- module: keyword to start the module definition.
- module_name: the name you give to your module.
- port_list: list of input/output ports inside parentheses.
- Module body: contains declarations and logic.
- endmodule: keyword to end the module.
verilog
module module_name (port1, port2, ...); // Port declarations input port1; output port2; // Internal logic endmodule
Example
This example defines a simple module named and_gate with two inputs and one output. It shows how to declare ports and assign output using an AND operation.
verilog
module and_gate (input a, input b, output y); assign y = a & b; endmodule
Common Pitfalls
Common mistakes when defining modules include:
- Forgetting the
endmodulekeyword to close the module. - Not declaring ports properly as
input,output, orinout. - Mismatching port names between the module header and declarations.
- Using semicolons incorrectly after the port list.
verilog
/* Wrong way: missing endmodule and port declarations */ module wrong_module (a, b, y) assign y = a & b; /* Right way: proper declarations and endmodule */ module right_module (input a, input b, output y); assign y = a & b; endmodule
Quick Reference
| Keyword | Purpose |
|---|---|
| module | Starts module definition |
| endmodule | Ends module definition |
| input | Declares input ports |
| output | Declares output ports |
| inout | Declares bidirectional ports |
| assign | Assigns values to wires |
Key Takeaways
Start a module with the 'module' keyword and end with 'endmodule'.
Declare all ports explicitly as input, output, or inout.
Keep port names consistent between the header and declarations.
Use 'assign' for continuous assignments inside the module.
Always close your module properly to avoid syntax errors.