VHDL Generics
Quick Syntax
Here's how you declare generics at the top of your design source file:
entity data_bus is
generic(
ADDR_BIT_WIDTH : integer range 1 to 16 := 8;
DATA_BIT_WIDTH : integer range 1 to 32 := 32);
port(
clk : in std_logic;
reset : in std_logic;
addr : in std_logic_vector(ADDR_BIT_WIDTH-1 downto 0);
data : out std_logic_vector(DATA_BIT_WIDTH-1 downto 0));
end data_bus;
...........
signal data_buffer : std_logic_vector(DATA_BIT_WIDTH-1 downto 0);
And here is how you use generics when you instantiate your module in your top level:
BUS1 : entity work.data_bus
generic map (
ADDR_BIT_WIDTH => 16,
DATA_BIT_WIDTH => 16)
port map (
clk => clk,
reset => reset,
addr => bus1_addr,
data => bus1_data);
Purpose
Generics are a great way to create modular code that can be quickly changed to accomodate a wide variety of designs.
For example, you can use generics to set std_logic_vector bit widths for such things as addresses and data. Another example is using them to drive for generate loops to instantiate N number of modules.
By using generics, you can have one common design that you can use for almost any situation for a specific type of interface. As you are coding, you should always be thinking about how to make your source code more modular so that you can re-use it in the future for a similar design.
That way, as you advance as a coder, you are building a bigger and bigger library of your own modules that have already been simulated and proven out in hardware. It exponentially increases your speed and productivity in executing a design.
Generics are the main method to do this in VHDL.
Best Practices
1. Use generics to make your code modular so that you can design for re-use in mind. Consider the different sizes of signals that might occur in the future for similar designs and make your code where it can solve the problem for a wide variety of situations.
2. For generics that are integers, it's a good idea to set a range where if a top instantiation sets it out of range, the compile will fail. This way you can limit what the design source is used for based on what you have simulated and tested.
3. Always set your generics to a default value. That way if someone wants to use the defaults only, they can omit the generic map portion in the top level instantiation. If they want to change only a few, they only have to list the ones they want to over-ride in the generic map.